Author Posts

August 10, 2015 at 8:04 am

I have a powershell module to help with error handling. When i call methods in the error handling module from other modules the global $error variable appears empty even when it is not. I thought the $error variable was global and as such i would be able to do some thing like the following.

In the below code the method Do-Something in the module 'Some other module' throws an exception or non terminating error which it elevates to a terminating exception. I would assume that the Display-Errors method that is called would be able to see the errors in the $error variable but it can not.

# call do-something
Do-Something


# Module - Some other module *********************
function Do-Something
{
    Begin
    {
        # make all errors rterminating
        $ErrorActionPreference = 'Stop'
    }
    Process
    {
        if ($pscmdlet.ShouldProcess("Target", "Operation"))
        {
            try{
                throw 'boom'
                #blah blah blah
            }
            catch
            {
                Display-Errors
            }
        }
    }
    End
    {
    }
}
# End of Module - Some other module *************



# Module - Error handling ***************************
function Display-Errors
{    
    Write-Host( $Error | Format-List -Force | Out-String) -ForegroundColor Red -BackgroundColor Black 
}
# End of Module - Error handling ******************

August 11, 2015 at 5:26 am

$error is like any other variable – it's scoped. So if it gets changed in a module, that is only visible in the module. The best practice would be to capture that in the module in which it occurs, and pass it as a parameter to your error-handling routine. Functions shouldn't rely on global variables as a data-passing mechanism anyway, as a general rule.

August 11, 2015 at 6:26 am

Thanks for your help Don. That is what I have done. In general I don't rely on global scope as a mechanism for passing data about but I assumed that a parameter of global scope would behave more like a static property in C# and be available to and synchronized between all calling code.

Thanks once again though.