How to suppress non terminating errors in PowerShell scripts

Greetings!  Here is a tip on how to suppress non terminating errors in your PowerShell scripts.  First you should understand what a non terminating error actually is.  These are errors that do not stop the Cmdlet processing.  For example, if you are trying to remove a machine from Active Directory that does not exist you would get the below error.

Remove-ADComputer -Identity Machine001
Remove-ADComputer : Cannot find an object with identity: ‘Machine001’ under: ‘DC=deluxe,DC=com’.
At line:1 char:1
+ Remove-ADComputer -Identity Machine001
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Machine001:ADComputer) [Remove-ADComputer], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: ‘Machine001’ under: ‘DC=deluxe,DC=com’.,Microsoft.ActiveDirectory.Managemen
   t.Commands.RemoveADComputer

You might try to use the ErrorAction parameter to suppress the error.  However you will quickly find this does not work.

Remove-ADComputer -Identity Machine001 -ErrorAction SilentlyContinue
Remove-ADComputer : Cannot find an object with identity: ‘Machine001’ under: ‘DC=deluxe,DC=com’.
At line:1 char:1
+ Remove-ADComputer -Identity Machine001 -ErrorAction SilentlyContinue
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Machine001:ADComputer) [Remove-ADComputer], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: ‘Machine001’ under: ‘DC=deluxe,DC=com’.,Microsoft.ActiveDirectory.Managemen
   t.Commands.RemoveADComputer

Why didn’t this work?  Yep, you guessed it… this is a non terminating error.  You are so smart!  What you need to do is set the $ErrorActionPreference.  This is one of many PowerShell Preference Variables that you can use to customize the environments behavior.

$ErrorActionPreference = ‘SilentlyContinue’

So instead of this…

erroractionpreference01

You get this…

erroractionpreference02

Have a great day!

Your email is never published or shared. Required fields are marked *

*

*