我不确定您对代码有什么担忧。设置时看起来很不错,除了语法错误$folder
:
你为什么还要尝试使用$_.CreationTime
作为文件夹时间戳?只需使用当前日期:
$folder = (Get-Date -Format "yyyyMMdd")
See 在 PowerShell 中格式化时间戳 https://winscp.net/eng/docs/script_formatting_timestamp_batch_file在 WinSCP 文档中。
我也没有看到设置点$folder
and $backupPath
in the params
堵塞。将其移至params
block. 如果您无论如何都想要这个,那么您在后面缺少了一个逗号$folder
任务。
除此之外,您的代码应该可以工作。
您无法通过使用内置的 PowerShell(或更确切地说 .NET)FTP 功能来简化它,因为它没有像 WinSCP .NET 程序集那样强大的命令。
我将代码写为:
$localPath = "C:\source\local\path\*"
$remotePath = "/dest/remote/path/"
$folder = (Get-Date -Format "yyyyMMdd")
$backupPath = "C:\local\backup\path\$folder"
# If today's folder doesn't exist, create it
if (!(Test-Path $BackupPath))
{
New-Item -ItemType Directory -Force -Path $BackupPath | Out-Null
}
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::ftp
HostName = "ftp.example.com"
UserName = "username"
Password = "password"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath)
# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
Write-Host ("Upload of $($transfer.FileName) succeeded, " +
"moving to backup")
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host ("Upload of $($transfer.FileName) failed: " +
"$($transfer.Error.Message)")
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
基于上传成功后将本地文件移至其他位置 https://winscp.net/eng/docs/script_local_move_after_successful_upload.