Error and ErrorVariable

The Error variable is a collection (ArrayList) of handled and unhandled errors raised in the PowerShell session.

Testing the content of error variables

Testing the content of an error variable is not a robust way to test for error conditions.
As the variable fills with both handled and unhandled errors, it's indeterminate at best. Error variables continue to have value when debugging less obvious problems with code.

The error collection can be cleared using the Clear method:

$Error.Clear() 

The most recent error is first in the list:

$Error[0] 

Errors will be added to the collection except when ErrorAction is set to Ignore.

The ErrorVariable parameter can be used to name a variable that should be used, as well as Error for a specific command. The Error variable, the value in the variable name, is an ArrayList.

The following function writes an Error variable. When ErrorVariable is used, the errors are added to the named variable:

function Invoke-Something { 
    [CmdletBinding()] 
    param ( ) 
 
    Write-Error 'Failed' 
}
Invoke-Something -ErrorVariable InvokeError -ErrorAction SilentlyContinue

The errors stored in the variable can be inspected:

PS> $InvokeError
Invoke-Something : Failed
At line:1 char:1
+ Invoke-Something -ErrorVariable InvokeError -ErrorAction SilentlyCont ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-Something
ErrorVariable is never null

If no errors occur, the variable will still be created as an ArrayList, but the list will contain no elements. That the list exists means using the variable as an implicit Boolean is flawed, that is, the $null -eq $InvokeError statement will return false.
The Count property might be inspected instead, using $InvokeError.Count -eq 0.

Error messages written to an ErrorVariable are duplicated in Error:

PS> $error[0]
Invoke-Something : Failed
At line:1 char:1
+ Invoke-Something -ErrorVariable InvokeError -ErrorAction SilentlyCont ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-Something

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.4.206