How to set exit code when an exception occurs

MyScript.ps1:

exit 1 

MyThrow.ps1:

 throw "test" 

Running in PowerShell:

 & ".\MyScript.ps1" Write-Host $LastExitCode # Outputs 1 Clear-Variable LastExitCode & ".\MyThrow.ps1" Write-Host $LastExitCode # Outputs nothing 

How to set the correct exit code when creating an exception?

+13
source share
3 answers

No. When you make an exception, you expect someone to handle it. So that someone can stop the execution and set the exit code. For instance:

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

If you have nothing to catch, you should not drop it first, but exit immediately (with the correct exit code).

+12
source

You can set the exit code and throw an error using System.Environment:

 # set final exit code [System.Environment]::ExitCode = 1 # throw unhanded exception to terminate script throw "test" 
0
source

Running mythrow.ps1 inside powershell will set $? to false, and add $ error to the array of the object. Running it with another powershell process will set $ lastexitcode to 1.

 PS C:\> powershell mythrow.ps1 PS C:\> $lastexitcode 1 
0
source

Source: https://habr.com/ru/post/982998/


All Articles