使用 PowerShell 从 SFTP 服务器下载文件 [英] Download files from SFTP server using PowerShell

查看:75
本文介绍了使用 PowerShell 从 SFTP 服务器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 PowerShell 脚本将文件从 SFTP 服务器下载到本地计算机.

用于下载的 API/库需要能够监控传输结果、记录传输以及存档/移动下载的文件.

提前致谢.

解决方案

PowerShell 或 .NET 框架不支持 SFTP.因此,您必须使用外部 SFTP 库.


一种可能性(您在问题中标记了自己)是

(我是 WinSCP 的作者)

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.

解决方案

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;

(I'm the author of WinSCP)

这篇关于使用 PowerShell 从 SFTP 服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆