如何配置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
相关产品推荐
相关产品推荐

