Using Try Catch and Exit Codes in PowerShell Scripts

Robust error handling is one great feature of PowerShell. This can be accomplished in a few ways the simplest way would be to use an if statement to check that a specific result was accomplished after a command has been ran for example


 All though this will work it is not the best method and it only give use limited information about why the new-item command failed. To get a better error handling experience we can use a try catch block. In short a try catch block will try to run an command and if there is an error it will catch the error and do something.


In the above example we use the try catch block to create a new folder, notice the -ErrorAction Stop parameter we added to the command. We add the -ErrorAction stop parameter so that the command in the try statement will stop and not continue to the Write-Host command. The other big difference between the try catch block and the if statement is the Write-Error "$_" command we put in the Catch. This command will write the error of the command the failed. This will tell us exactly why the command failed and not just that the command failed. 

In the below example I have ran a script with the above code in it so we can see how the catch will show


A Try Catch Block is great to have an exit code set depending on what happens, Setting an exit code in PowerShell is very easy simply use Exit <Number>. Most applications use 0 to represent a success and 1 as a general failure so we will add these to your code 


The exit code is stored in the $LASTEXITCODE variable and can be called from the same PowerShell secession that the script ran in. 


By adding try catch blocks and exit codes to your script you provide a better way for end users and other applications to interact with your script. 

Comments