PowerShell PSDefaultParamterValues

Viewed 22

I came across this private error variable example recently.

#hiding errors:
$ErrorActionPreference = 'SilentlyContinue'
#telling all cmdlets to use a private variable for error logging:
$PSDefaultParameterValues.Add('*:ErrorVariable', '+myErrors')
#initializing the variable:
$myErrors = $null

#do stuff:
Stop-Service -Name Spooler
dir c:\gibtsnichtabcs

#check errors at end USING PRIVATE VARIABLE:
$myErrors

I just want to understand the $PSDefaultParameterValues.Add line above as to how prepending + to the myErrors variable name makes it cumulative. Thanks.

1 Answers

The $PSDefaultParameterValues line causes PowerShell to pass argument -ErrorVariable +myErrors to all cmdlets or advanced functions.

The documentation for the -ErrorVariable common parameter says:

By default, new error messages overwrite error messages that are already stored in the variable. To append the error message to the variable content, type a plus sign (+) before the variable name.

So the "cumulative" behaviour is implemented in PowerShell's handling of the common parameters.

Related