PowerShell Exit Code

This past month I've been working with some PowerShell scripts. I've been learning a lot about them; much of it works as I would expect, some sort of cross between a shell language and a .NET scripting language.

But every now and again I run into something surprising, and I think some of these make for good posts.

Below are a couple of ways to properly return an error code from PowerShell when using the -File parameter (see also this). There are a number of ways to actually run powershell code, but this is a good topic on its own for a future entry, so we'll keep it short.

There are three seemingly obvious ways to return a value from a script: the return statement, the exit statement, or by letting an exception escape.

Here is a little script that we'll be using to try things out.


param ($how)
if ($how -Eq "return") { return 42 }
if ($how -Eq "exit") { exit 42 }
if ($how -Eq "throw") { throw 42 }
42

Save this to foo.ps1 in your temp directory and run through this.


PS temp-path> Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted
PS temp-path> powershell -file .\foo.ps1
1001
PS temp-path> echo $LASTEXITCODE
0
PS temp-path> powershell -file .\foo.ps1 return
42
PS temp-path> echo $LASTEXITCODE
0
PS temp-path> powershell -file .\foo.ps1 exit
PS temp-path> echo $LASTEXITCODE
42
PS temp-path> powershell -file .\foo.ps1 throw
42
At temp-path\foo.ps1:4 char:25
+ if ($how -Eq "throw") { throw 42 }
+                         ~~~~~~~~
    + CategoryInfo          : OperationStopped: (42:Int32) [], RuntimeException
    + FullyQualifiedErrorId : 42

So exit and throwing can set the last exit code to a non-zero value, while returning or letting a non-zero expression finish the script won't do that.

Happy coding!

Tags:  powershell

Home