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?
Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script.
The $() is the subexpression operator. It causes the contained expressions to be evaluated and it returns all expressions as an array (if there is more than one) or as a scalar (single value).
Exit Code 1 is often caused by application errors that cause the application, and the entire container, to exit. If you determine that Exit Code 1 is caused by an application, you can experiment with various configuration options of the application to prevent it from exiting.
Using break in loopsWhen a break statement appears in a loop, such as a foreach , for , do , or while loop, PowerShell immediately exits the loop. A break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as foreach , for , or while , in a script.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With