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

时间:2018-01-17 23:24:05

标签: ftp sftp winscp winscp-net

免责声明#1:我在WinSCP forum上发布了此问题,但未收到任何回复,此问题对时间敏感。
免责声明#2:我将这个交叉帖子的合法性建立在Meta的主题advice上。
使用该序言...

到目前为止,我一直在使用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站点上?

1 个答案:

答案 0 :(得分:3)

WinSCP没有与-rename-move开关类似的功能。因此,在一个简单的脚本中实现此任务并不容易,以便它以事务方式运行(重命名并仅移动已成功下载的文件)

但您可以使用WinSCP .NET assembly中的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)")
    }
}

这个答案的一些参考是基于:

另见: