PowerShell Error Action Preference
The error action preference is the default rule for how PowerShell handles a command error. It applies to every command that does not set its own rule.
Stop turns an error into a catchable stop
With Stop, a failing command stops and catch runs. The script then keeps going after catch.
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try { Get-Item "/definitely-not-here-xyz" } catch { "Caught: " + $_.Exception.Message }
$ErrorActionPreference = $oldPreference
"Preference: " + $ErrorActionPreferenceContinue keeps the script going
With Continue, an error does not stop the script. The error message is sent away with 2>$null, so only the next line is shown.
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = "Continue"
Get-Item "/definitely-not-here-xyz" 2>$null
$ErrorActionPreference = $oldPreference
"Still running"SilentlyContinue hides the error
With SilentlyContinue, no error is shown and the script keeps going. The next line runs as normal.
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
Get-Item "/definitely-not-here-xyz"
$ErrorActionPreference = $oldPreference
"Still running"Example
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
"Preference: " + $ErrorActionPreference
try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message }
Get-Item "/definitely-not-here-xyz"
$ErrorActionPreference = $oldPreference
"Done"Key points
- Error action preference: the default rule for how a command error is handled.
- Stop: the rule that turns an error into a stopping error.
- Continue: the rule that shows the error and keeps the script going.
- SilentlyContinue: the rule that hides the error and keeps the script going.
- -ErrorAction: a flag on one command that beats the preference for that command.
In this example, the preference is set to SilentlyContinue, the first command overrides it with Stop and is caught, the second command stays silent, and the old preference is restored before Done prints.
Note
Save the old preference and restore it after your change, so later commands keep their normal rule.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which preference value hides the error and keeps the script going?