我使用此脚本通过 WinSCP 获取两个日期之间的文件。如何在控制台中打印哪些文件在远程计算机上找到,哪些文件未找到,因为目前我不确定所有文件是否已下载,因为两次之间文件可能丢失。 (类似于:如果我输入从 05.07.2023 到 07.07.2023 的日期;并且脚本在远程计算机上未找到一个或多个文件,则会在控制台中返回此消息“远程计算机上缺少日期 x 的文件 *.log;与“文件夹 $remotefolder 是否存在”相同)
# Set up session options
$options = @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = $User
Password = $Password
GiveUpSecurityAndAcceptAnySshHostKey = $true
}
try {
# Set up session options using first password
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
# Set up session options using second settings
$options['HostName'] = $vpnIP
$options['UserName'] = $User
$options['Password'] = $Password
try {
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
throw
}
}
# Date 1 START
do {
$date = $null
$today = Read-Host -Prompt ('Enter START date (inclusive) (e.g. {0}) [yyyy.MM.dd]' -f (Get-Date -Format "yyyy.MM.dd"))
try {
$date = Get-Date -Date $today -Format "yyyy-MM-dd" -ErrorAction Stop
'[OK] {0} Valid date - OK!' -f $date
}
catch {
'[X] {0} Invalid date!' -f $today
}
}
until ($date)
# Date 2 STOP
do {
$date1 = $null
Write-Host "Add +1 day" -ForegroundColor Red
$today1 = Read-Host -Prompt ('Enter END date (exclusive) (e.g. {0}) [yyyy.MM.dd]' -f (Get-Date -Format "yyyy.MM.dd"))
try {
$date1 = Get-Date -Date $today1 -Format "yyyy-MM-dd" -ErrorAction Stop
'[OK] {0} Valid date - OK!' -f $date1
}
catch {
'[X] {0} Invalid date!' -f $today1
}
}
until ($date1)
# ----- Date END
$session = New-Object WinSCP.Session
$file = "*.log"
$localPath = "\temp_files"
$remotePath = "/C:/log", "/C:/Back_up"
try {
# Connect
$session.Open($sessionOptions)
# Check exists folder
foreach ($remotePath in $remotePath)
{
if ($session.FileExists($remotePath))
{
Write-Host "[OK] Folder '$remotePath' exist" -ForegroundColor Green
# Transfer file
Write-Host "[i] '$date' - '$date1' > '$inputID' downloading..." -ForegroundColor Cyan
$session.GetFilesToDirectory($remotePath, $localPath, "*.log>=$date<=$date1").Check();
}
else
{
Write-Host "[X] INFO: Folder: '$remotePath' doesn't exist" -ForegroundColor Red
}
}
}
finally {
$session.Dispose()
}
谢谢你,
使用基本 WinSCP PowerShell 下载示例中的代码:
$transferResult =
$session.GetFilesToDirectory($remotePath, $localPath, "*.log>=$date<=$date1")
# Throw on any error
$transferResult.Check()
# Print results
foreach ($transfer in $transferResult.Transfers)
{
Write-Host "Download of $($transfer.FileName) succeeded"
}