Powershell fails to return proper exit code

一世执手 提交于 2020-01-01 08:21:21

问题


When executing a Powershell script (in 2.0) using the -File command line switch, and explicitly defining the input parameters in Param, the exit code is always "0" (never fails) instead of properly returning the defined or expected error code.
This does not occur when using the explicit parameter definitions and the -Command switch, however for extraneous purposes, I need to keep the -File switch in my scripts.

Any assistance with a workaround (that doesn't involve removing the explicit parameter definitions) would be extremely helpful.

Powershell "fails to return correct exit code":

exit1.ps1: Call script that explicitly defines parameters. Errorlevel is always 0, even if there are parts of the script that ungraciously fail.

param(
    [Parameter(mandatory=$true)][string]$arg1,
    [Parameter(mandatory=$true)][string]$arg2,
    [Parameter(mandatory=$true)][string]$arg3
);
exit 1;

Output:

C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\exit1.ps1 "one" "two" "three"

C:\temp\testnant>echo %errorlevel%
0




Now, lets try the same thing when modifying the param function to be less explicit:

Exit1LooseParam.ps1:

param(
    $arg1,
    $arg2,
    $arg3
);
exit 1;

Output (with three parameters):

C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\Exit1looseParam.ps1 "one" "two" "three"

C:\temp\testnant>echo %errorlevel%
1




It appears that when you explicitly define the input parameters, Powershell seems to "lose its freakin mind" for some reason and fails to return the proper exit code.

Does anyone have a workaround or be able to explain why this is happening?


回答1:


Hmm that's odd, I'd expect exit 1 to work in both cases. At least you can use this for both:

[Environment]::Exit(1)



来源:https://stackoverflow.com/questions/8902004/powershell-fails-to-return-proper-exit-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!