17.4. Using the $ErrorActionPreference variable

The $ErrorActionPreference variable specifies the action to take in response to an error occurring. The following values are supported:

  • SilentlyContinue — Don't display an error message continue to execute subsequent commands.

  • Continue — Display any error message and attempt to continue execution of subsequence commands.

  • Inquire — Prompts the user whether to continue or terminate the action

  • Stop — Terminate the action with error.

Set the $ErrorActionPreference variable to SilentlyContinue by using this command:

$ErrorActionPreference = "SilentlyContinue"

As you can see in Figure 17-13, the ForLoop.ps1 script runs to completion without displaying any error message. The error message is available in $Error[0] if you want to see it.

Figure 17.13. Figure 17-13

The default value of $ErrorActionPreference is Continue. When that is the setting, the appearance when running ForLoop.ps1 is the same as that shown in Figure 17-1.

When you set the value of $ErrorActionPreference to Inquire, execution stops when the error occurs, the error is described, and the user is prompted to decide what to do next:

Action to take for this exception:
Attempted to divide by zero.
[C] Continue  [I] Silent Continue  [B] Break  [S] Suspend  [?] Help (default is
"C"):

Figure 17-14 shows the results of executing ForLoop.ps1 with $ErrorActionPreference set to Inquire ...

Get Professional Windows® PowerShell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.