当单个文件上传失败时,使用 WinSCP .NET 程序集的批处理文件上传停止

Batch file upload with WinSCP .NET assembly stops, when a single file upload fails

我正在使用 WinSCP 连接到 FTP 并上传一堆文件,但我 运行 在文件上传失败时遇到问题,当脚本发生时停止,并且不会上传以下文件。我主要使用 WinSCP's documentation

中的代码
# Conectar
$session.Open($sessionOptions)

#Upload files
$transferResult = $session.PutFiles($origenSubida, $destinoSubida)

# Resultados de cada archivo
foreach ($transfer in $transferResult.Transfers)
{
    #looks if upload is correct
    if ($transfer.Error -eq $Null)
    {
        LogWrite ("$(Get-Date) upload complete {0} , changing folder" -f $transfer.FileName) 
        Move-Item $transfer.FileName $rutaArchivos
    }
    else
    {
        LogWrite ("$(Get-Date) Upload of {0} has failed: {1}" -f $transfer.Filename, $transfer.Error.Message)
    }
}

意外行为如下:

我在文件夹中有 4 个文件要上传,文件 1、2、3 和 4,如果我删除文件 3 的所有权限并且 运行 脚本,文件 1 和 2 将上传到FTP 然后他们被移动到另一个目录,然后脚本以文件 3 没有权限的错误结束,文件 4 没有上传。

我不确定我是否忽略了什么,即使脚本不能对 file3 执行任何操作,脚本是否应该继续?我不确定是否有另一种方法可以使单个文件的上传失败。

如果你想要自定义错误处理,你必须自己循环文件。

$localPath = "C:\local\path"
$remotePath = "/remote/path/"

$localFiles = Get-ChildItem -Path $localPath

foreach ($localFile in $localFiles)
{
    Write-Host "Uploading $($localFile.FullName)..."
    $sourcePath = [WinSCP.RemotePath]::EscapeFileMask($localFile.FullName)
    $transferResult = $session.PutFiles($sourcePath, $remotePath)

    if (!$transferResult.IsSuccess)
    {
        # Print error (but continue with other files)
        Write-Host ("Error upload file $($localFile.FullName): " +
            "$($transferResult.Failures[0].Message)")
    }    
}

Recursively download directory tree with custom error handling 的官方示例类似。