Don’t do that #17: Silent the errors with $ErrorActionPreference = ‘SilentlyContinue’

By | April 11, 2015

Don’t do that: It’s not recommended to silent the errors messages modifying the preference variable $ErrorActionPreference:
$ErrorActionPreference = 'SilentlyContinue'

Do that: Avoid to modify the default value of $ErrorActionPreference. By default, the value is $ErrorActionPreference = 'Continue'

First, because you could not be aware when an error occurs and second, it pollutes the user’s session by modifying the preference variable.
Doing that, all the cmdlets are affected because $ErrorActionPreference is a global preference variable.

PowerShell has two kinds of errors:

  • terminating (in case of error, the command execution stops, the entire pipeline fails)
  • non-terminating (in case of error, the command execution continue. For example, you have a text file with a list of 10 computers and you run a command for every computer. If the computer05 is offline, PowerShell still continue to the next computer06, computer07, …

Most of the cmdlets generate a non-terminating error (although there are some exceptions).

$ErrorActionPreference is a variable saying how PowerShell will treat non-terminating errors.

Let’s explain that better with some examples:

Example 1: You have set  $ErrorActionPreference = 'SilentlyContinue'

It seems to work (no error displayed but in fact, it failed because the computer 0123456789 doesn’t exist).

powershell-set-erroractionpreference-silentlycontinue

By setting $ErrorActionPreference = 'SilentlyContinue' , you will receive no error messages and it is hard to see it the command successfully completed or failed.

Example 2: You have  $ErrorActionPreference = 'Continue'

Here, we can see an error BUT our warning message is not displayed.

powershell-set-erroractionpreference-continue

Example 3: You have set  $ErrorActionPreference = 'SilentlyContinue' and -ErrorAction Stop

Our warning message was not displayed so we need to use -ErrorAction Stop
When adding -ErrorAction Stop , it forces any non-terminating error to become a terminating error (in order to catch them).

powershell-set-erroractionpreference-continue-erroraction-stop

You can get the last error exception with : $Error[0].Exception.GetType().FullName

powershell-set-erroractionpreference-continue-warning-catch-last-error

The automatic global variable $Error contain terminating and non-terminating errors.

You can be more specific and generate a warning message based on the exception error (you can add multiple catch block).

powershell--erroractionpreference-continue-warning-catch-last-error


previous-buttonnext-button

One thought on “Don’t do that #17: Silent the errors with $ErrorActionPreference = ‘SilentlyContinue’

  1. Pingback: Don’t do that #18 : Use a loop For to get the line number - Powershell Guru

Leave a Reply

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