PowerShell – Using WinSCP to copy files to/from Linux machines

It is possible to copy files to/from a linux machine using Powershell. This can be done using a free tool called winscp.

Winscp is actually a gui based tool, but you can use it from

# I created this script using the following as an inspiration:
# http://winscp.net/eng/docs/library_powershell#installing_the_assembly

# Load WinSCP .NET assembly
[Reflection.Assembly]::LoadFrom(“c:\path\to\WinSCPnet.dll”) | Out-Null

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = $ServerName
$sessionOptions.UserName = $Username
$sessionOptions.Password = $password
#$sessionOptions.SshHostKeyFingerprint = “ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx” # this feature is desabled in the next line.
# Note I disabled the above line, and enabled the line below using instructions from:
# http://winscp.net/eng/docs/library_sessionoptions
$sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = $true

$session = New-Object WinSCP.Session
# note for more info, see http://winscp.net/eng/docs/library_session

# Connect
$session.Open($sessionOptions)

# Set transfer mode to binary
# note, for more info, see: http://winscp.net/eng/docs/library_transferoptions
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

Now to send files to the linux machine, do:

$session.PutFiles("$SourcePath", "$DestinationPath", $False, $transferOptions)

And to retrieve files, do:

$session.GetFiles("$SourcePath", "$DestinationPath", $False, $transferOptions)

Putting it altogether, we have:

[Reflection.Assembly]::LoadFrom(“C:\path\to\winscp-dll\WinSCPnet.dll”) | Out-Null

$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "linuxservername" 
$sessionOptions.UserName = "username"
$sessionOptions.Password = "password"

$sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = $true

$session = New-Object WinSCP.Session

$session.Open($sessionOptions)


$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

$SourcePath = "C:\Temp\testfile.txt"
$DestinationPath = "/tmp/testfile.txt"

$session.PutFiles("$SourcePath", "$DestinationPath", $False, $transferOptions)

The folder that contains your WinSCPnet.dll file will also need to contain the WinSCP.exe file as well. You can download my copy of both of these files.

Useful links:

http://winscp.net/eng/docs/library_sessionoptions#properties

http://winscp.net/eng/docs/library_powershell