Powershell $ Error object is not immediately written to PSM1

I am facing a particular issue with Powershell. I catch the exception in the catch block, but the global $ Error object is not populated.

A trivial example where this will behave as expected:

function Bar { Foo } function Foo { try { $Error.Clear() throw "Error!" } catch { "Caught an error - current error count $($Error.Count)" } finally { "Cleaning up - current error count $($Error.Count)" } } 

The output is as you would expect if you call Bar

 Caught an error - current error count 1 Cleaning up - current error count 1 

The code I'm having problems with is almost identical, except that it loads Foo from the module. Not sure if this is a mistake, or just something I don’t understand (I will need to check my Powershell in the action book!)

If I save Foo in a module - Foo.psm1

 function Foo { try { $Error.Clear() throw "Error!" } catch { "Caught an error - current error count $($Error.Count)" } finally { "Cleaning up - current error count $($Error.Count)" } } Export-ModuleMember -Function Foo 

Then I do the following

 Import-Module .\Foo.psm1 $Error.Clear() "Current error count $($Error.Count)" Foo "Current error count $($Error.Count)" 

The end result

 Current error count 0 Caught an error - current error count 0 Cleaning up - current error count 0 Current error count 1 

Note that Foo no longer sees the changes made to $ Error. Thus, code modulation changes the behavior of error propagation. Can anyone reflect on the reasoning behind this?

I should note that I can get a specific caught exception through the $ _ automatic variable, but I'm looking to get the whole collection at this point in the call stack.

+7
source share
2 answers

I hadn’t noticed this before, but perhaps the $ error assembly is bound to the module, like any other variables. Try comparing the values ​​of the following two clearly restricted variables at key points in your test script:

 "Errors - Global: {0}; Module: {1}" -f $global:error.count, $script:error.count 

Let me know how you are doing.

+7
source

As Ethan said, you need to take a look at $ global: error to see all the errors. Modules always have their own $ error variable, but it is (mostly) not used.

background: at some point, we looked at isolation errors that occurred in the module code, up to the module area, but ultimately decided to add all the errors to the global error collection, since this is essentially an error log (for example, in the in-memory event log .) Unfortunately, a module error with the $ error scope was not removed before the release, so you need to use the global scope qualifier to access the "real" $ error variable.

Bruce Payet, Microsoft Corporation

+9
source

All Articles