我有时会注意到一些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
}
1条答案
按热度按时间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
正确的语法为: