我需要使用PowerShell脚本将文件从SFTP服务器下载到本地计算机。
将用于下载的API /库需要能够监控传输结果,记录传输,以及存档/移动下载的文件。
提前致谢。
答案 0 :(得分:9)
PowerShell或.NET框架中没有SFTP支持。所以你必须使用外部SFTP库。
一种可能性(您在问题中标记了自己)是WinSCP .NET assembly。有一篇关于using WinSCP from PowerShell的文章。
甚至有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甚至可以generate a PowerShell SFTP download code,如上所述:
(我是WinSCP的作者)