Don’t do that #10: Use Exception.Message to catch an error in Catch block

By | April 10, 2015

Don’t do that: The following code catch the error with “Exception.Message”:


Do that: I prefer to use the exception error in the catch block.

You can have multiple Catch block (each section handles a specific error).

Check the exception error code (Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) and then put that inside the catch block.

The commands inside the try section must have their parameter -ErrorAction set to Stop (or $ErrorActionPreference set to Stop, although not recommended to change this built-in global variable). Doing that, it will turn an error into a terminating error. It is important that the command is processing only one item at a time.

Tip: To get the last error exception (the first item is the most recent error):

Note: The Try/Catch/Finally construct was introduced since PowerShell v2.  In PowerShell v1, the Trap construct was used for error handling.


previous-buttonnext-button

One thought on “Don’t do that #10: Use Exception.Message to catch an error in Catch block

  1. Pingback: Don’t do that #11 : Reload a module with Remove-Module and Import-Module - Powershell Guru

Leave a Reply

Your email address will not be published. Required fields are marked *