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 is indeterminate at best. Error variables continue to have value when debugging less obvious problems with code.

The collection can be cleared using:

$Error.Clear() 

The most recent error is first in the list:

$Error[0] 

Errors will be added to the collection except when the 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. If ErrorVariable is used, the errors are added to the variable name:

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

Executing the function with a named variable will make the errors available:

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 following statement will return false:
$null -eq $InvokeError
The Count property might be inspected instead:
$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
3.146.34.146