Simple example
The following simple script tries to demonstrate the effect of the value of the
$errorActionPreference
variable by opening three
registry keys.
Of these three keys, the second one,
HKEY_LOCAL_MACHINE\SAM\SAM
, requires
SYSTEM privileges to be opened. Because in most cases, these privileges are not granted to an ordinary user, this key cannot be opened.
The three statements that try to open the registry key are guarded by
try
… catch
statements.
function open-registryKey($name) {
$regKey = get-item $name
write-host "Opened $($regKey.Name)"
}
try {
open-registryKey hklm:\SOFTWARE
open-registryKey hklm:\SAM\SAM
open-registryKey hklm:\SYSTEM
}
catch {
write-host "Caught error $_"
}
When the script is run with the default of $errorActionPreference
(continue), an error message is written and the script continues to also open the third key.
PS:\> .\errorActionPreference.ps1
Opened HKEY_LOCAL_MACHINE\SOFTWARE
get-item : Requested registry access is not allowed.
At …
[…]
Opened
Opened HKEY_LOCAL_MACHINE\SYSTEM
However, if the value of $errorActionPreference
is set to stop, the error is caught in the exception handler and the third key is not opened.
PS:\> $ErrorActionPreference='stop'
PS:\> .\errorActionPreference.ps1
Opened HKEY_LOCAL_MACHINE\SOFTWARE
Caught error Requested registry access is not allowed.
Using the -errorAction parameter of a cmdlet to set the value of $errorActionPreference
In a
cmdLet, the
common parameter -errorAction
sets the value for
$errorActionPreference
in the scope of the cmdlet, as is demonstrated with the following simple example:
function eap {
[cmdletbinding()]
Param()
write-host "errorActionPreference: $errorActionPreference"
}
When this function (cmdlet) is executed, it prints the value that was passed via -errorAction
:
PS C:\> eap -errorAction inquire
errorActionPreference: Inquire