Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the exit code when throwing an exception

Tags:

MyScript.ps1:

exit 1 

MyThrow.ps1:

throw "test" 

Execution in PowerShell:

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

How do I set a proper exit code when throwing an exception?

like image 843
D.R. Avatar asked Feb 25 '15 16:02

D.R.


People also ask

How do you set an exit code in Python?

You can set an exit code for a process via sys. exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.

How do you write an exit code in powershell?

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. It is in form of boolean values, with 0 for success and 1 for failure.

What does finished with exit code 0 mean?

What does process finished with exit code mean? "process finished with exit code 0" -! It means that there is no error in your code. Nothing to worry about. YouTrack Workflow commented 27 Sep 2021 09:00.


2 Answers

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).

like image 189
Ansgar Wiechers Avatar answered Oct 06 '22 22:10

Ansgar Wiechers


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

like image 24
Kino101 Avatar answered Oct 06 '22 23:10

Kino101