So you need to send files via FTP from Powershell in an automated fashion? Good news is its pretty easy with WinSCP and its .Net Assembly. The example on WinSCP’s website is good but its not a working example as far as production is concerned. Lets wrap it around a function to make it a bit more useful.
First you will need to grab the files from WinSCP’s website here: WinSCP .Net Assembly
Next we will need to load the .Net Assembly:
1 |
Add-Type -Path "PathToWinSCPnet.dll" |
Using the complete example from WinSCP we can tweak a few of the parameters to wrap a function around and make the method repeatable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function Send-FTP([string]$user, [string]$pass, [string]$site, [string]$key, [string]$source, [string]$dest){ try { # Setup session options $sessionOptions = New-Object WinSCP.SessionOptions $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp $sessionOptions.HostName = "$site" $sessionOptions.UserName = "$user" $sessionOptions.Password = "$pass" $sessionOptions.SshHostKeyFingerprint = "$key" $session = New-Object WinSCP.Session try { # Connect $session.Open($sessionOptions) # Upload files $transferOptions = New-Object WinSCP.TransferOptions $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary $transferResult = $session.PutFiles("$source", "$dest", $False, $transferOptions) # Print results foreach ($transfer in $transferResult.Transfers) { Write-Host -foregroundcolor green ("Upload of {0} succeeded" -f $transfer.FileName) } } finally { # Disconnect, clean up $session.Dispose() } #exit 0 } catch [Exception] { Write-Host $_.Exception.Message exit 1 } } |
You can now call that function as many times as you need to send data via WinSCP to an FTP server with powershell! Stay tuned for another post regarding downloading data from an FTP server with WinSCP.