Download files from SFTP server using PowerShell Download files from SFTP server using PowerShell powershell powershell

Download files from SFTP server using PowerShell


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;

enter image description here

(I'm the author of WinSCP)