在使用 WinSCP 和 PowerShell 上传文件之间暂停

Pause between file uploads with WinSCP and PowerShell

我有下面的 PowerShell 脚本,非常感谢任何帮助。

该脚本从网络驱动器中抓取文件名以 COKA_*" 开头的文件并上传到 SFTP 站点。

问题: 目标站点不喜欢批量接收所有文件,而是一次接收一个文件。每次文件传输之间有 60 秒的延迟。

可以在脚本或迭代中的何处添加此延迟以一次仅推送一个文件并延迟 60 秒?非常感谢您的帮助。

param (

    $localPath = "U:\####\COKA_*", # Source, one or more files generated at on a request
    $remotePath = "/from_/feast/Outbound/", #Destination file location
    $backupPath = "U:\####\Archive", # archive file destination
)

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "E:\######\WinSCP\WinSCPnet.dll"

    # Set up session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "123.456.78.901"
        UserName = "iamencrypted"
        SshHostKeyFingerprint = "ssh-rsa 2048 DYPA3BjRCbKLosI5W9iamdefinatlydencrypted"
        SshPrivateKeyPath = "\#####\###\###\##\FTP\######\#####\########.ppk"
    }

    $sessionOptions.AddRawSettings("AgentFwd", "1")

    $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 Archive"
                # Upload succeeded, move source file to Archive
                Move-Item -force $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
}

那么你不能使用 Session.PutFiles 和文件掩码。

您必须自己找到要上传的文件,然后为每个文件分别调用 Session.PutFiles,并在 (Start-Sleep).

之间暂停

为此使用 Get-ChildItem

$files = Get-ChildItem $localPath

foreach ($file in $files)
{
    $localFilePath = $file.FullName
    $transferResult = $session.PutFiles($localFilePath, $remotePath)

    if ($transferResult.IsSuccess)
    {
        Write-Host "Upload of $localFilePath succeeded, moving to Archive"
        # Upload succeeded, move source file to Archive
        Move-Item -Force $localFilePath $backupPath
    }
    else
    {
        $err = $transferResult.Failures[0].Message
        Write-Host "Upload of $localFilePath failed: $err"
    }

    Start-Sleep -Seconds 60
}