Correctly Returning Exit Codes

by Feb 27, 2012

When you launch a PowerShell script from outside PowerShell, you may want to return an exit code to the caller so that the caller knows if your script ran ok. You can send back an exit code by using the statement exit xy where “xy” is a numeric value.

Here is a sample script to test drive this:

exit $code

Save this in a .ps1 script file, then launch cmd.exe, and run your script:

Powershell.exe noprofile file pathtoscript.ps1 1234

This returns 1234 (or whatever code you submitted to your script when you called it). The reason why so many people have trouble with returning exit codes is that they miss the –file parameter:

Powershell.exe noprofile pathtoscript.ps1 1234

Without –file, powershell.exe returns either 0 or 1. That’s because now your code is interpreted as a command, and when the command returns an exit code other than 0, PowerShell assumes it failed. It then returns its own exit code, which is always 0 (command ran fine) or 1 (command failed).

Twitter This Tip! ReTweet this Tip!