'Download files from SFTP server using PowerShell
I need to download files from SFTP server to a local machine using a PowerShell script.
The API/library that will be used for the download needs to be able to monitor results of the transfer, log the transfer, and also to archive/move the downloaded files.
Thanks in advance.
Solution 1:[1]
There's no SFTP support in PowerShell or .NET framework. So you have to use an external SFTP library.
One possibility (which you have tagged yourself in your question) is WinSCP .NET assembly. There's an article on using WinSCP from PowerShell.
There's even a code example in PowerShell for SFTP download:
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Download files
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$remotePath = "/home/user/*";
$localPath = "d:\download\*";
$transferResult =
$session.GetFiles($remotePath, $localPath, $False, $transferOptions)
# Throw on any error
$transferResult.Check()
# Print results
foreach ($transfer in $transferResult.Transfers)
{
Write-Host "Download of $($transfer.FileName) succeeded"
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
WinSCP GUI can even generate a PowerShell SFTP download code, like the one above, for your specific session settings and transfer options:
- Login to your server with WinSCP GUI;
- Select the files for download in the remote file panel;
- Navigate to the target directory in the local file panel;
- Invoke the Download command;
- On the Transfer options dialog, go to Transfer Settings > Generate Code;
- On the Generate transfer code dialog, select the .NET assembly code tab; Choose PowerShell language.
(I'm the author of WinSCP)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Francesco Mantovani |