使用 -File 参数调用时,如何让 powershell 返回正确的退出代码? [英] How can I get powershell to return the correct exit code when called with the -File argument?
本文介绍了使用 -File 参数调用时,如何让 powershell 返回正确的退出代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果使用 -File 参数调用,则发生错误时,Powershell 将返回 0 退出代码.这意味着我的构建在不应该是绿色的时候是绿色的:(
Powershell is returning a 0 exit code, when an error has occurred, if called with the -File argument. Which means my build is green when it shouldn't be :(
例如:
(在 wtf.ps1 中)
(in wtf.ps1)
$ErrorActionPreference = "Stop";
$null.split()
(命令)
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 已经)
(I've tried pretty much every idea from the first 2 pages of this: https://www.google.co.uk/search?q=powershell+file+argument+exit+code already)
推荐答案
在脚本中,使用带有您选择的数字的 exit 关键字:
In the script, use the exit keyword with a number of your choice:
exit 34
这是我用来测试这个的脚本:
Here's the script I used to test this:
## 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
这篇关于使用 -File 参数调用时,如何让 powershell 返回正确的退出代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文