Error handling in Powershell

Hey there!

I have recently played around with an error handling, also using functions.

You can explicitly define the behaviour of the script and how it should handle errors using an $ErrorActionPreference variable. You will typically set it to either of following:

  • Continue (default) – in this case an error will be displayed, but the script will attempt to continue
  • Stop – the script will stop the execution and report an error
  • SilentlyContinue – it will ignore the error (without displaying it) and continue execution

Good. But how about functions, exit (return) codes and error messages? I recently found the cmdlet Write-Error.

Take a look at one example how to do it:

$ErrorActionPreference = "Stop"

function test () {
   Write-Error "Testing failed!"
}

try {
   test
} catch {
   $err = $_.Exception.Message
   Write-Host "An error occured: $err"
}

 

Let me know if it helped you.

 

Cheers!

Robot(ICT) guy

Published by

Lukas Vu

I started in IT with my own business since high school providing automated and centralized hosting solutions to end customers. Nowadays I'm focusing on corporate area, analyzing, managing and improving customer's IT environments. My main focus nowadays is automation and architectural improvements.

Leave a Reply

Your email address will not be published.