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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.