首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Jenkins中构建成功,即使WinSCP PowerShell传输脚本失败

在Jenkins中构建成功,即使WinSCP PowerShell传输脚本失败
EN

Stack Overflow用户
提问于 2022-09-20 10:44:18
回答 1查看 54关注 0票数 1

我有时会注意到,一些Jenkins构建在其输出中有一个错误,没有以一个错误结尾(例如,一个退出1),但是成功了。

这来自于WinSCP $transferResult.Check()函数。

例如,使用我们将CSV文件上载到SFTP远程目录的脚本之一:

是否可以在此函数中添加一个条件,如果exit 1中有错误,该条件以$transferResult.Check()结尾

这样,它就能阻止Jenkins以成功的构建结束。

我的PowerShell文件

代码语言:javascript
运行
复制
# 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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-20 13:13:01

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

正确的语法是:

代码语言:javascript
运行
复制
$session = New-Object WinSCP.Session

try
{
    # Your code
}
catch 
{
    Write-Host -ForegroundColor red "Error: $($_.Exception.Message)"
    exit 1
}
finally
{
    $session.Dispose()
}

exit 0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73785428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档