Expand Minimize

Avoid usage of $ErrorActionPreference

Using $ErrorActionPreference can create some strange behavior by purposfuly disabling errors from happening. Potential errors should be checked for with an if statement before they can happen, or be caught in a try-catch-finally.

CheckId SPC059101
TypeName AvoidUsageOfErrorActionPreference
Severity CriticalWarning
Type PowerShell File

Bad Practice

$old_ErrorActionPreference = $ErrorActionPreference;
$ErrorActionPreference = 'SilentlyContinue';
if((Get-PSSessionConfiguration -Name "foo" -ErrorAction SilentlyContinue) -eq $null) {
else {
$ErrorActionPreference = $old_ErrorActionPreference;
Good Practice
  $wc = new-object System.Net.WebClient
catch [System.Net.WebException],[System.IO.IOException]
  "Unable to download MyDoc.doc from http://www.contoso.com."
  "An error occurred that could not be resolved."

Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.