Is an exception from a .NET method a terminating or not-terminating error?
The Try
block turns the .NET exception into a terminating error, so you can enclose your .NET call in such a block:
Try { Class::RunSomeCode() } Catch { Throw }
So in your example your tst
function becomes
function tst { 1 | write-host; Try { $a::bl() } Catch { Throw } 2 | Write-host }
And your .NET exception will now be terminating.
Yeah, this came up on the PowerShell MVP email list earlier this year. PowerShell changes its error handling behavior for .NET exceptions depending on whether or not there is an outer try/catch. This is just speculation but I'm guessing that this was for simple scripting scenarios. That is, if the scripter (admin) messes up calling a .NET method and that generates an exception, the PowerShell team didn't want that to cease execution of the entire script. Once V2 came along and introduced proper try/catch I'm guessing they had to revisit that decision and came up with the current compromise.
That said, working around this is a pain as you've discovered. You could set $ErrorActionPreference to Stop
at the script level and then for every cmdlet that can generate non-terminating errors use the -ErrorAction Continue
parameter. Or you could put all of your .NET invocations within an advanced function(s) and then call that function(s) with the parameter -ErrorAction Stop
. I wish there was a better answer but after reviewing that MVP thread, I didn't see any better solutions.