我有时会注意到,一些Jenkins构建在其输出中有一个错误,没有以一个错误结尾(例如,一个退出1),但是成功了。
这来自于WinSCP $transferResult.Check()
函数。
例如,使用我们将CSV文件上载到SFTP远程目录的脚本之一:
是否可以在此函数中添加一个条件,如果exit 1
中有错误,该条件以$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
}
发布于 2022-09-20 13:13:01
try
块的语法无效。catch
从未发生过,因为exit 0
以前无条件地中止您的脚本。如果不是exit 0
,脚本就会在catch
上失败,因为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://stackoverflow.com/questions/73785428
复制相似问题