当使用-File参数调用时,如何让PowerShell返回正确的退出代码?

gra*_*hay 15 powershell exit-code

如果使用-File参数调用,Powershell将在发生错误时返回0退出代码.这意味着我的构建是绿色的,它不应该是:(

例如:

(在wtf.ps1中)

$ErrorActionPreference = "Stop";   
$null.split()
Run Code Online (Sandbox Code Playgroud)

(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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

(我已经尝试了前两页的每个想法:https://www.google.co.uk/search?q = popershell + file +argument + exit + code)

Sha*_*evy 12

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

exit 34
Run Code Online (Sandbox Code Playgroud)

这是我用来测试这个的脚本:

## 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
Run Code Online (Sandbox Code Playgroud)


Lar*_*ens 9

这是一个众所周知的问题.解决方法是使用-File调用脚本,使用-Co​​mmand参数(并添加;如果您还有自己的退出代码,则退出$ lastexitcode)或将其转换为Shay显示的退出代码或使用下面的陷阱的示例.有关更多信息,请参见此处

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

$ErrorActionPreference = "Stop";   
$null.split()
Run Code Online (Sandbox Code Playgroud)

  • 这种解决方法在Jenkins中运行良好.我只使用了以下Windows PowerShell命令:PowerShell -File"srcipt.ps1"; exit $ lastexitcode; (2认同)