You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置WinSCP PowerShell脚本,使Jenkins在传输失败时标记构建失败?

解决WinSCP上传错误未触发Jenkins构建失败的问题

问题根源

原脚本的catch块位置错误,写在了finally和exit 0之后,导致$transferResult.Check()抛出的异常根本不会被捕获,脚本会直接执行exit 0,让Jenkins误判构建成功。

修正后的脚本

调整try-catch-finally结构位置,确保异常能被捕获并触发exit 1:

# 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."
}
catch 
{
    Write-Host -ForegroundColor red "Error: $($_.Exception.Message)"
    exit 1
}
finally
{
    $session.Dispose()
}
exit 0

修改说明

  • 将catch块移至try之后、finally之前,确保$transferResult.Check()抛出的上传错误能被捕获
  • 捕获异常后输出错误信息并执行exit 1,强制Jenkins标记构建失败
  • 保留原脚本中"本地无文件时正常终止"的逻辑,该场景不属于构建失败

内容的提问来源于stack exchange,提问作者Victor Leclerc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:25:22