【问题标题】:Handling Jenkins Groovy script exceptions处理 Jenkins Groovy 脚本异常
【发布时间】:2017-12-01 05:20:39
【问题描述】:

我正在执行一个 C# exe,CRS.exe,我希望它返回一个非零值,例如 -1。我正在使用 ps 来取回价值,并在一个阶段内拥有它:

  try{            
      pcode = (powershell(returnStdout: true, script: 'return Invoke-Expression -Command \" .\\perfmon\\CRS.exe hello \"'))''
      echo "Pcode =  ${pcode} "
      }
  catch (err) {echo err.message }
  echo "Pcode =  ${pcode} "

根据这篇文章,“通常情况下,以非零状态代码退出的脚本会导致步骤失败并出现异常。” -- Jenkins pipeline bubble up the shell exit code to fail the stage 我想处理这个非零结果,异常处理程序是唯一的方法吗? 以上运行结果:

    Running PowerShell script
tester arg = hello    
[Pipeline] echo
script returned exit code -1
[Pipeline] echo
Pcode =  null 

有趣的是,char 返回似乎没问题?这会返回而不抛出异常

 icode = (powershell(returnStdout: true, script: 'return Invoke-Expression -Command \'.\\perfmon\\zipInstaller.ps1 -urlString ' + fileContents + "'"))
                echo "icode =  ${icode} "

Results in 
[Pipeline] {
[Pipeline] powershell
[Chris] Running PowerShell script
[Pipeline] echo
icode =  -5

我想从 exe 中获取返回码,并据此管理我的 groovy 管道流。任何见解将不胜感激。

【问题讨论】:

  • 非零退出代码可能会导致命令在写入 pcode 变量之前失败。如果您想对此进行测试,请尝试在 powershell 调用之前为 pcode 分配一个默认值。如果它为空,则说明您的命令有问题。如果它是默认值,则您的命令在写入变量之前失败。
  • 另外,我认为命令末尾的'' 是一个错字。

标签: c# jenkins groovy


【解决方案1】:

不要使用returnStdout: true,而是尝试使用returnStatus: true。它应该始终返回退出代码。如果您一次需要 powershell 命令的输出(没有returnStdout,它只会将输出打印到 Jenkins 日志),则没有那么有用,但作为一种解决方法,您可以将输出通过管道传输到文件,然后将其打印出来.

另一种选择(但它很丑,所以我不推荐它)是从 bat 命令调用 Powershell。 bat 应该掩盖 powershell 命令的错误代码,这样 Jenkins 就不会兴奋和自动失败,你仍然会得到标准输出。如果你真的想要错误代码,显然不是很有帮助。你的线看起来像

pcode = (bat(returnStdout: true, script: 'Powershell.exe "return Invoke-Expression -Command \" .\\perfmon\\CRS.exe hello \"'"))

这条线需要稍微改进一下,但它可能是另一种选择。

【讨论】:

  • 感谢您的建议,这可能是最好的方法。我试图变得贪婪,一口气把它全部搞定,被不投掷的 ps 宠坏了。
  • @Chris 我已经用另一个可能有效的选项编辑了答案。虽然很丑。
猜你喜欢
  • 2016-09-21
  • 1970-01-01
  • 2016-11-02
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 2017-06-28
相关资源
最近更新 更多