Q. How can I avoid receiving errors from PowerShell commands when data is missing?

A. PowerShell has an error action option that you can add to commands. The switch

-ea 0

will cause PowerShell to take no action when it encounters an error. This can be useful if you're checking for data that may not exist and would normally return an error.

For example, the command

get-hotfix -id KB974332 -computername savdaldc11

will return an error if the specified computer doesn't have hotfix KB974332 installed. If you instead use the command

get-hotfix -id KB974332 -computername savdaldc11 -ea 0

nothing will happen and you won't get an error message.

The -ea 0 switch is actually equivalent to the command -ErrorAction SilentlyContinue, as in

get-hotfix -id KB974332 -computername savdaldc11 -ErrorAction SilentlyContinue

Other options for the error action are stop (1), continue (2) and inquire (3). The default action is continue, which you can check by viewing the $ErrorActionPreference value with the command

$ErrorActionPreference

The stop option halts execution in the event of an error and inquire asks the user whether to continue or halt.

Related Reading:



Check out hundreds more useful Q&As like this in John Savill's FAQ for Windows. Also, watch instructional videos made by John at ITTV.net.
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish