Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top