Friday, June 03, 2016

Using Powershell and WinSCP to SFTP upload

There may be an occasion where you need to send your files somewhere using SFTP. Perhaps as an automated, scheduled task:

It is not necessary to install the full WinSCP application stack. The automation pack should be used for automation. Download WinSCP automation from .NET assembly / COM library on the https://winscp.net/eng/download.php page and place on the server.

This pack contains an executable and the DLL that interact with each other. Just put the DLL and EXE together.

Script:

[System.Reflection.Assembly]::LoadFrom('C:\PATH\WinSCPnet.dll')
Add-Type -Path "C:\PATH\WinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl("sftp://USER:PASS@;fingerprint=FINGERPRINT@SFTP.SITE.COM")
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
$session.PutFiles("C:\PATHTOUPLOAD\[file.xyz] or [* for all]", "/[upload folder if necessary]/").Check()
$session.Dispose()

If you downloaded the files, make sure you unblock:



Now, simply configure your Scheduled Task. Don't forget to set the Security Options.



Program/Script:                        powershell.exe
Add arguments (optional):        -ExecutionPolicy Bypass -File "C:\PathToYour\File.ps1"


No comments: