Catching errors
As we’ve discovered, errors contain lots of useful information we can use to make our code run smoothly. While Get-Error
and the $Error
variable are useful for real-time troubleshooting, we need to have another way to deal with errors when we are writing scripts.
Try/Catch/Finally
The best way to handle terminating errors in PowerShell is with a Try
/Catch
/Finally
statement. This statement allows us to set up alternate courses of action, depending on whether or not an error occurred. The statement consists of a mandatory Try
block, which contains code that might generate an error, and then either a Catch
block, a Finally
block, or both. The Catch
block will run if the code in the Try
block generates a terminating error; this is our exception handler. The code in the Finally
block will run regardless of whether an error is generated or not; this block is used for any code that may be required to clean up after the code in the Try
block. We don’t see...