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.
Ethan J. Brown
source share