在PowerShell中仅使用WinSCP下载新文件 [英] Download only new files with WinSCP in PowerShell
问题描述
如何下载最新文件或发布了一定天数的文件?导入包含 Source 和 Destination 列的CSV文件.需要检查路径是否存在/文件是否存在,并且仅下载新文件.
How could I download the latest files, or files that were posted a certain amount of days? Importing a CSV file that contains a Source and a Destination column. Needs to check, if the path exists/file exists and only download new files.
脚本现在正在将所有文件移动到相应的文件夹中-但是一旦我再次运行该脚本,它就不会仅下载新文件.
Script right now is moving all the files to the correspondent folder - but once I run the script again, its not downloading only new files.
这是CSV文件的示例:
Here's an example of the CSV file:
try{
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::sftp
HostName = "xxxxx"
UserName = "xxxxr"
Password = "xxxxxxx"
PortNumber = "xx"
GiveUpSecurityAndAcceptAnySshHostKey = $true
}
$session = New-Object WinSCP.Session
try{
# Connect
$session.Open($sessionOptions)
# Download files
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
Import-Csv -Path "C:\movefiles.csv" -ErrorAction Stop | foreach{
Write-Host $_.Source
Write-host $_.Destination
$transferResult =
$session.GetFiles($_.Source, $_.Destination, $False, $transferOptions)
# Throw on any error
$transferResult.Check()
# Print results
$smtpBody = ""
foreach ($transfer in $transferResult.Transfers){
Write-Host "Download of $($transfer.FileName) succeeded"
$smtpbody += " Files : ( $transfer.filename - join ', ')" +
" Current location: $($_.Destination) "
}
Send-Mail Message @smtpMessage -Body $smtpbody
}
finally {
# Disconnect, clean up
$session.Dispose()
}
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
}
}
CSV文件示例:
Source, Destination
/client1/Business/2019, C:\test\test1
/client2/Reporting/2018, C:\test\test2
推荐答案
如果您的Source
和Destination
是纯目录路径,则只需将Session.GetFiles
替换为 Session.SynchronizeDirectories
:
If your Source
and Destination
are plain directory paths, you can simply replace Session.GetFiles
with Session.SynchronizeDirectories
:
Import-Csv -Path "C:\movefiles.csv" -ErrorAction Stop | foreach {
$synchronizationResult = $session.SynchronizeDirectories(
[WinSCP.SynchronizationMode]::Local, $_.Destination, $_.Source, $False)
$synchronizationResult.Check()
foreach ($download in $synchronizationResult.Downloads)
{
Write-Host "File $($download.FileName) downloaded"
}
}
另请参见WinSCP常见问题解答如何仅传输新文件/修改过的文件?
See also WinSCP FAQ How do I transfer new/modified files only?
这篇关于在PowerShell中仅使用WinSCP下载新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!