如何在使用“-File”参数调用PowerShell时使其返回正确的退出代码?

17

当使用 -File 参数调用 PowerShell 时,即使发生错误也会返回 0 退出代码。这意味着我的构建状态变成了绿色,但实际上应该是失败的 :(

例如:

(在 wtf.ps1 中)

$ErrorActionPreference = "Stop";   
$null.split()

(cmd)

powershell -file c:\wtf.ps1  
You cannot call a method on a null-valued expression.
At C:\wtf.ps1:3 char:12
+ $null.split <<<< ()
    + CategoryInfo          : InvalidOperation: (split:String) [], ParentConta
   insErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull


echo %errorlevel%  
0

powershell c:\wtf.ps1  
You cannot call a method on a null-valued expression.
At C:\wtf.ps1:3 char:12
+ $null.split <<<< ()
    + CategoryInfo          : InvalidOperation: (split:String) [], ParentConta
   insErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull


echo %errorlevel%  
1

有什么想法吗?

(我已经尝试了这个链接的前两页中几乎所有的想法:https://www.google.co.uk/search?q=powershell+file+argument+exit+code

2个回答

13
在脚本中,使用exit关键字和你选择的数字:
exit 34

这是我用来测试的脚本:

## D:\Scripts\Temp\exit.ps1 ##
try{
    $null.split()
}
catch
{
    exit 34
}

exit 2
#############################

# launch powershell from cmd 
C:\> powershell -noprofile -file D:\Scripts\Temp\exit.ps1
C:\>echo %errorlevel%
34

如果是终止错误,退出语句就不会被调用 :( 而且,即使我使用 try/catch 和 exit >0,如果我使用 -File 调用它,我也会失去退出代码。 - grahamrhay
嗯,你的例子对我来说有效。但是,我的构建仍然是绿色的。我会看看有什么不同的地方。 - grahamrhay

12

这是一个已知的问题。解决方法包括使用-File选项调用脚本,使用-Command参数(如果您还有自己的退出代码,则需要添加; exit $lastexitcode),或像Shay所示的将它们转换为退出代码的方式,或者使用下面的trap示例。有关更多信息,请参见此处

trap
{
    $ErrorActionPreference = "Continue";   
    Write-Error $_
    exit 1
}

$ErrorActionPreference = "Stop";   
$null.split()

2
这个解决方法在Jenkins中运行良好。我只是使用了以下Windows PowerShell命令:PowerShell -File "srcipt.ps1"; exit $lastexitcode; - Ola Eldøy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接