[英]Download files from SFTP server using PowerShell
I need to download files from SFTP server to a local machine using a PowerShell script.我需要使用 PowerShell 脚本将文件从 SFTP 服务器下载到本地计算机。
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.将用于下载的 API/库需要能够监控传输结果、记录传输以及存档/移动下载的文件。
Thanks in advance.提前致谢。
There's no SFTP support in PowerShell or .NET framework. PowerShell 或 .NET 框架中不支持 SFTP。 So you have to use an external SFTP library.
所以你必须使用外部 SFTP 库。
One possibility (which you have tagged yourself in your question) is WinSCP .NET assembly .一种可能性(您在问题中标记了自己)是WinSCP .NET assembly 。 There's an article on using WinSCP from PowerShell .
有一篇关于使用 PowerShell 中的 WinSCP的文章。
There's even acode example in PowerShell for SFTP download : PowerShell 中甚至还有一个用于 SFTP 下载的代码示例:
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: WinSCP GUI 甚至可以为您的特定会话设置和传输选项生成 PowerShell SFTP 下载代码,如上面的代码:
(I'm the author of WinSCP) (我是WinSCP的作者)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.