Returning Exit Code from Script

by May 18, 2009

When running a PowerShell script, you may want to return a numeric exit code to the caller to indicate failure or success. You should use the "exit" statement to return whatever numeric exit code you want. The following line in a script would exit the script and return "10" as exit code:

exit 10

There are two gotchas. First, never use "exit" in your interactive PowerShell console or else you will close it. Secondly, how can the caller of a PowerShell script actually receive the exit code?

This is easy if you launch a PowerShell script from within PowerShell. The exit code is stored in the automatic variable $LASTEXITCODE.

If you launch PowerShell scripts from a different environment, such as from a batch file, things are tricky. Normally, you would launch your script like this:

powershell.exe -noprofile C:path_to_scriptscript.ps1

You will only receive either 0 or 1 when you now check the exit code from within your batch file using the %ERRORLEVEL% environment variable. This is because PowerShell by default only differentiates between failure and success. To actually pass on the return code submitted by your script, you will have to explicitly read it from $LASTEXITCODE and exit PowerShell with this code, like this:

powershell.exe -noprofile C:path_to_scriptscript.ps1$LASTEXITCODE