【问题标题】:How can I get powershell to return the correct exit code when called with the -File argument?使用 -File 参数调用时,如何让 powershell 返回正确的退出代码?
【发布时间】:2012-05-16 14:17:24
【问题描述】:

如果使用 -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

【问题讨论】:

    标签: powershell exit-code


    【解决方案1】:

    在脚本中,使用带有您选择的数字的 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
    

    【讨论】:

    • 如果是终止错误,则永远不会调用退出 :( 而且,即使我尝试/捕获并退出 >0,如果我使用 -File 调用它,我也会丢失退出代码。
    • 嗯,你的例子对我有用。然而,我的构建仍然是绿色的。我会看看我能不能弄清楚有什么不同。
    【解决方案2】:

    它是a known problem。解决方法是使用 -File 调用脚本,使用 -Command 参数(如果您也有自己的退出代码,则添加 ; exit $lastexitcode)或将它们转换为退出代码,如显示的Shay 或使用下面的陷阱的示例。请参阅here 了解更多信息。

    trap
    {
        $ErrorActionPreference = "Continue";   
        Write-Error $_
        exit 1
    }
    
    $ErrorActionPreference = "Stop";   
    $null.split()
    

    【讨论】:

    • 此解决方法在 Jenkins 中运行良好。我只是使用了以下 Windows PowerShell 命令: PowerShell -File "srcipt.ps1";退出 $lastexitcode;
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 2017-10-11
    • 1970-01-01
    • 2021-04-23
    • 2015-10-01
    • 2016-05-20
    • 1970-01-01
    • 2016-11-30
    相关资源
    最近更新 更多