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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access