$ $ Null variable error, but $ _ contains error in Catch

I have a PS module that contains several scripts for individual functions. There is also a β€œlibrary” script with a number of helper functions called by the functions used in the module.

Let the external ReadWeb function be ReadWeb , and it uses the ParseXML helper function.

This week I ran into an error handling issue in the ParseXML internal helper function. This function contains try / catch, and in catch I will interrogate:

$Error[0].Exception.InnerException.Message

... to pass the error back to the outside as a variable and determine if ParseXML is ParseXML .

In a specific case, I was getting an indexing error when I called ReadWeb . The root cause was the $Error object in the Catch block in ParseXML $Null returned.

I changed the error handling to check $Error -eq $Null , and if so, use $_ in Catch to determine what the error message is.

My question is: what would lead to $Error $Null inside Catch ?

+7
powershell error-handling
source share
2 answers

$error is an automatic variable processed by Powershell: 3rd Β§ LONG DESCRIPTION in about_Try_Catch_Finally .

It is considered as the context of the Catch block, so it is available as $_ . Since the Catch block is a different block than Try, the automatic variable $error reset and evaluates to $null .

+1
source share

$ error and try / catch are different animals in PowerShell.

try / catch catches error interrupts, but does not catch Write-Error (because it does not interrupt).

$ error - a list of all detected errors (including swallowed when -ErrorAction is used).

$ _ is the current error in the try / catch block.

I would suggest that your main function calls Write-Error, and you want it to be clean in try / catch. To make this also a trailing error, use -ErrorAction Stop.

0
source share

All Articles