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'
1 2 3 4 5 6 7 8 9 10 |
$ErrorActionPreference = 'SilentlyContinue' try { Get-WmiObject -Class win32_process -ComputerName 0123456789 } catch { Write-Warning 'Computer offline or not responding' } |
It seems to work (no error displayed but in fact, it failed because the computer 0123456789 doesn’t exist).
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.
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).
1 2 3 4 5 6 7 8 9 10 |
$ErrorActionPreference = 'Continue' try { Get-WmiObject -Class win32_process -ComputerName 0123456789 -ErrorAction Stop } catch { Write-Warning 'Computer offline or not responding' } |
You can get the last error exception with : $Error[0].Exception.GetType().FullName
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ErrorActionPreference = 'Continue' try { Get-WmiObject -Class win32_process -ComputerName 0123456789 -ErrorAction Stop } catch [System.Runtime.InteropServices.COMException] { Write-Warning 'Warning 1' } catch [System.Management.ManagementException] { Write-Warning 'Warning 2' } |