17.6. Using Common Parameters

Many cmdlets support the common parameters ErrorAction and ErrorVariable. These are particularly relevant to the situation where errors can occur or are likely to occur.

17.6.1. Using the ErrorAction Parameter

The -errorAction parameter specifies the error action for a cmdlet. It overrides the value set in the $ErrorActionPreference variable.

To show how you can use the ErrorAction parameter, enter these commands with your current working folder set to one that does not contain a file called Fred.txt.

First confirm the value of $ErrorActionPreference by running the following command:

$ErrorActionPreference

Then run each of the following commands:

get-childitem Fred.txt -ErrorAction SilentlyContinue ; write-host "We got here"
get-childitem Fred.txt -ErrorAction Continue; write-host "We got here"
get-childitem Fred.txt -ErrorAction Stop; write-host "We got here"
get-childitem Fred.txt -ErrorAction Inquire; write-host "We got here"

The commands use the four possible enumerated values for the ErrorAction parameter—SilentlyContinue, Continue, Stop, and Inquire. Figure 17-23 shows the results with blank lines added to help readability.

Figure 17.23. Figure 17-23

Notice that the value of $ErrorActionPreference is Continue.

With the ErrorAction parameter set to SilentlyContinue, the error message is not displayed and execution continues to the write-host ...

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.