Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
Ratnesh Sharma Avatar asked Oct 10 '17 07:10

Ratnesh Sharma


1 Answers

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.

enter image description here

(I'm the author of WinSCP)

like image 174
Martin Prikryl Avatar answered Nov 12 '22 23:11

Martin Prikryl