即使WinSCP PowerShell传输脚本失败,Jenkins中的构建也会成功

tmb3ates  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(182)

我有时会注意到一些Jenkins构建在其输出中有错误,而不是以错误结束(例如,以exit 1结束),而是以成功结束。
这来自WinSCP $transferResult.Check()函数。
例如,使用我们的一个脚本将CSV文件上传到SFTP Remote目录:

如果$transferResult.Check()中有错误,是否可以向此函数添加一个以exit 1结尾的条件?
这样,它可以阻止Jenkins以成功的构建结束。
我的PowerShell文件


# Load WinSCP .NET assembly

Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

# Set up session options

$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = ""
    UserName = ""
    Password = ""
    Timeout = New-TimeSpan -Seconds 300
}

# Set local directories

$LocalDir = "\\localdir\*"
$RemoteDir = "/remotedir/"

$session = New-Object WinSCP.Session

try
{
    # Check if the local directory exists
    if (Test-Path -Path $LocalDir) {
        "Local directory $LocalDir exists! All good."
    } else {
        "Error: Local directory $LocalDir doesn't exist. Aborting"
        exit 1
    }

    # Check if the local directory contain files
    if((Get-ChildItem $LocalDir | Measure-Object).Count -eq 0)
    {
        "Local directory $LocalDir has currently no CSV files. Stopping script."
        exit 0
    } else {
        "Local $LocalDir contains CSV files. Starting now SFTP Upload Session..."
    }

    # Connect to the FTP server

    $session.Open($sessionOptions)
    $session.Timeout = New-TimeSpan -Seconds 300

    # Upload the files
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Automatic
    $transferOptions.FileMask = "*.csv, |*/";

    $transferResult = $session.PutFiles($LocalDir, $RemoteDir, $true, $transferOptions)

    # Throw on any error
    $transferResult.Check()

    # Print results
    foreach ($transfer in $transferResult.Transfers)
    {
        Write-Host -ForegroundColor green "Upload of $($transfer.FileName) to remote SFTP directory $RemoteDir succeeded."
    }

    Write-Host "$($transferResult.Transfers.Count) file(s) in total have been transferred."
}
finally
{
    $session.Dispose()
}
exit 0
catch 
{
    Write-Host -ForegroundColor red "Error: $($_.Exception.Message)"
    exit 1
}
ljo96ir5

ljo96ir51#

您的try区块有无效的语法。catch永远不会发生,因为exit 0之前会无条件地中止您的指令码。如果没有exit 0,指令码会在catch上失败,因为catch必须在finally之前。
请参阅https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally
正确的语法为:

$session = New-Object WinSCP.Session

try
{
    # Your code
}
catch 
{
    Write-Host -ForegroundColor red "Error: $($_.Exception.Message)"
    exit 1
}
finally
{
    $session.Dispose()
}

exit 0

相关问题