Suppressing Errors

by Nov 26, 2020

With cmdlets, suppressing errors seems easy: simply add the –ErrorAction Ignore parameter.

However, it turns out that this doesn’t suppress all errors. It only suppresses errors that the cmdlet chose to handle. Especially security-related exceptions still show.

If you want to suppress all errors, you can pipe exceptions to null by appending „2>$null“:

PS> Get-Service foobar 2>$null

This works for all commands and even raw method calls. Simply enclose the code with curly brackets and call it via the „&“ call operator:

PS> [Net.DNS]::GetHostEntry('notPresent')
MethodInvocationException: Exception calling "GetHostEntry" with "1" argument(s): "No such host is known."

PS> & {[Net.DNS]::GetHostEntry('notPresent')} 2>$null


Twitter This Tip! ReTweet this Tip!