我有時注意到一些 Jenkins 構建在其輸出中有錯誤,但沒有以錯誤結束(例如,退出 1)但成功。
這來自 WinSCP$transferResult.Check()功能。
例如,使用我們將 CSV 檔案上傳到 SFTP 遠程目錄的腳本之一:

是否可以向此函式添加一個條件,以exit 1if 中的錯誤結尾$transferResult.Check()?
這樣,它可以阻止 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
}
uj5u.com熱心網友回復:
您的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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/510170.html
