我這裡有一個腳本,可以將 SFTP 檔案從一個位置複製到另一個位置,該腳本工作正常,但我想更改該腳本,以便它只複製尚不存在的檔案。有點像 powershell 新手,所以任何幫助將不勝感激。
cd "c:\Program Files (x86)\WinSCP\" # location of .NET assembly ddl file
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "192.168.xxx.xxx"
$sessionOptions.UserName = "xxxx"
$sessionOptions.Password = "xxxx"
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx"
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
$stamp = Get-Date -f "yyyyMMdd"
$fileName = "export_$stamp.txt"
$remotePath = "/home/user/john/reports"
$localPath = "\\fileserver\reports\"
if ($session.FileExists($remotePath))
{
if (!(Test-Path $localPath))
{
Write-Host (
"File {0} exists, local backup {1} does not" -f
$remotePath, $localPath)
$download = $True
}
if ($download)
{
# Download the file and throw on any error
$session.GetFiles($remotePath, $localPath).Check()
Write-Host "Download to backup done."
}
}
else
{
Write-Host ("File {0} does not exist yet" -f $remotePath)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
非常感謝。
答案1
您從 WinSCP 範例中取得的腳本Session.GetFiles
僅針對單一文件而設計。您已嘗試將其彎曲以同步目錄。那是行不通的。
若要同步目錄,請使用Session.SynchronizeDirectories
:
# Synchronize files
$synchronizationResult = $session.SynchronizeDirectories(
[WinSCP.SynchronizationMode]::Local, $localPath $remotePath)
# Throw on any error
$synchronizationResult.Check()