.netpowershellpowershell-2.0sftpwinscp

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.


Solution

  • 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:

    enter image description here

    (I'm the author of WinSCP)


    Another way is to invoke OpenSSH sftp (the one commonly used on Linux systems). OpenSSH comes built-in in recent versions of Windows 10 and Windows 11.