How to set the exit code when throwing an exception How to set the exit code when throwing an exception powershell powershell

How to set the exit code when throwing an exception


You don't. When you throw an exception you expect someone to handle it. That someone would be the one to terminate execution and set an exit code. For instance:

try {  & ".\MyThrow.ps1"} catch {  exit 1}

If there is nothing to catch your exception you shouldn't be throwing it in the first place, but exit right away (with a proper exit code).


Becareful:

With Powershell 4 and less:

When an exception is thrown, exit code remains at 0 (unfortunately)

With Powershell 5 and up:

When an exception is thrown, exit code defaults to 1


Actually you can set the code also with throw, just put it before throw.

Contents of the script: Throw.ps1

exit 222throw "test"

Output:

PS C:\> .\Throw.ps1PS C:\> $LASTEXITCODE222

If you run it like this:

powershell .\Throw.ps1

The output will be as follows:

PS C:\> powershell .\Throw.ps1PS C:\> $LASTEXITCODE1

But here is the thing, powershell exit codes should be either 0 or 1,anything else, finally will give you result of 1.

Another interesting thing to mention, if to try $? after you run the script,if true or false, the result depends of what you want to put in there.exit 0 --> true, exit 1 --> false

Here it is an example:

Content of the script: Throw_1.ps1

exit 1throw "test"

Output:

PS C:\> .\Throw_1.ps1PS C:\> $?False

Content of the script: Throw_0.ps1

exit 0throw "test"

Output:

PS C:\> .\Throw_0.ps1PS C:\> $?True

As you can see it is just what you need or want to achieve.