用于下载、重命名和移动文件的 WinSCP 脚本

A WinSCP script to download, rename, and move files

免责声明 #1:我在 WinSCP 的 forum but haven't received any replies and this issue is time-sensitive.
Disclaimer #2: I'm basing the legitimacy of this cross-post on advice 上发布了这个问题,该问题是从 Meta 中找到的。
随着序言...

到目前为止,我一直在使用 WS_FTP 但想切换到 WinSCP。 我正在尝试将此 WS_FTP 脚本转换为 WinSCP:

"C:\Program Files (x86)\Ipswitch\WS_FTP 12\wsftppro.exe"
-s "sftp://USERNAME:PASSWORD@ftpus.pointclickcare.com/USERNAME/logs/*.sqb"
-d "local:C:\PccDataRelay\LogDownloads\"
-rename tx_[yyyy]-[mm]-[dd]_[hh]-[tt]-[ss]_[OnlyName].[OnlyExt]
-move "/USERNAME/logs/transferred/"

我已经能够部分转换它:

cd C:\PccDataRelay\TestDownloads

"C:\Program Files (x86)\WinSCP\winscp.com" /ini=nul /log=C:\PccDataRelay\AuditLogs\incremental_download.log /command ^
    "open sftp://USERNAME:PASSWORD@ftpus.pointclickcare.com/USERNAME/logs/ -hostkey=""ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx""" ^
    "get /USERNAME/logs/*.sqb" ^
    "exit"

但只有 下载 文件。我怎样才能重命名移动原始文件,同时将它们留在FTP网站上?

WinSCP 没有类似于 -rename-move 开关的功能。因此,在一个简单的脚本中实现这个任务并不容易,因此它的行为是事务性的(重命名和移动仅成功下载的文件)


但是你可以使用 WinSCP .NET assembly from a PowerShell script.

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "ftpus.pointclickcare.com"
    UserName = "USERNAME"
    Password = "PASSWORD"
    SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}

# Connect
Write-Host "Connecting..."
$session = New-Object WinSCP.Session
$session.SessionLogPath = "C:\PccDataRelay\AuditLogs\incremental_download.log"
$session.Open($sessionOptions)

# Download files
$transferResult =
     $session.GetFiles("/USERNAME/logs/*.sqb", "C:\PccDataRelay\LogDownloads\*")

# Process source files
foreach ($transfer in $transferResult.Transfers)
{
    # Success or error?
    if ($transfer.Error -eq $Null)
    {
        $newName =
            "/USERNAME/logs/transferred/tx_" +
            (Get-Date -Format "yyyy-MM-dd-hh-mm-ss") + "_" +
            [IO.Path]::GetFileName($transfer.FileName)
        Write-Host (
            "Download of $($transfer.FileName) succeeded, moving to backup $newName")
        $session.MoveFile($transfer.FileName, $newName)
    }
    else
    {
        Write-Host (
            "Download of $($transfer.FileName) failed: $($transfer.Error.Message)")
    }
}

此答案基于的一些参考文献:

另请参阅: