Download files from SFTP server using PowerShell

Ratnesh Sharma picture Ratnesh Sharma · Oct 10, 2017 · Viewed 25.2k times · Source

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.

Answer

Martin Prikryl picture Martin Prikryl · Oct 10, 2017

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
 
        $transferResult =
           $session.GetFiles("/home/user/*", "d:\download\*", $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;

enter image description here

(I'm the author of WinSCP)