WinSCP automation with powershell
Powershell can be used to automate the upload and download of files from sftp servers using the .NET assembly
Setup Session:
Setup the SFTP session using the following code, you will need to have the winscp automation package stored on the server somewhere:
# Define the path to the WinSCP .NET assembly DLL
$winscpPath = "C:\Automation\WinSCP-6.1.2-Automation\WinSCPnet.dll" # Update this path as needed
# Load the WinSCP .NET assembly
Add-Type -Path $winscpPath
# Create a SessionOptions object with SFTP settings
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $sftpHost
PortNumber = $sftpPort
UserName = $sftpUsername
Password = $sftpPassword
SshHostKeyFingerprint = "<ssh fingerprint of the sftp server>"
}
Once you have the session options configured you can connect to the SFTP server using the following command:
# Connect to the SFTP server
$session.Open($sessionOptions)
Get details of files on server
Use the enumerateremotefiles method to get the details of the files on the sftp server
$remoteFiles = $session.EnumerateRemoteFiles($remotePath, $null, [WinSCP.EnumerationOptions]::AllDirectories)
Upload Files
You can upload files using the PutFiles method:
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$session.PutFiles("$uploadpath\*", "$uploadDestination/", $false, $transferOptions)
the parameters are as follows: local path to files to upload, destination directory on sftp server, remove files from source on successful transfer, transfer options
Download files
files can be downloaded using the GetFiles method:
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$session.GetFiles($($file.FullName), "$localPath\$($file.name)", $false, $transferOptions)