Tuesday, May 3, 2011

Can I get detailed exception stacktrace in PowerShell?

Runing such script:

 1: function foo()
 2: {
 3:    bar
 4: }
 5: 
 6: function bar()
 7: {
 8:     throw "test"
 9: }
10: 
11: foo

I see

test
At C:\test.ps1:8 char:10

Can I get a detailed stack trace instead?

At bar() in C:\test.ps1:8
At foo() in C:\test.ps1:3 
At C:\test.ps1:11
From stackoverflow
  • There is the automatic variable $StackTrace but it seems to be a little more specific to internal PS details than actually caring about your script, so that won't be of much help.

    There is also Get-PSCallStack but that's gone as soon as you hit the exception, unfortunately. You could, however, put a Get-PSCallStack before every throw in your script. That way you get a stack trace immediately before hitting an exception.

    I think one could script such functionality by using the debugging and tracing features of Powershell but I doubt it'd be easy.

    JasonMArcher : We should file an enhancement request (if it hasn't already been submitted) to have this added automatically to exceptions.
  • There is a function up on the PowerShell Team blog called Resolve-Error which will get you all kinds of details

    Note that $error is an array of all the errors you have encountered in your PSSession. This function will give you details on the last error you encountered.

    function Resolve-Error ($ErrorRecord=$Error[0])
    {
       $ErrorRecord | Format-List * -Force
       $ErrorRecord.InvocationInfo |Format-List *
       $Exception = $ErrorRecord.Exception
       for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException))
       {   "$i" * 80
           $Exception |Format-List * -Force
       }
    }
    
  • You can not get a stack trace from exceptions of the PowerShell code of scripts, only from .NET objects. To do that, you will need to get the Exception object like one of these:

    $Error[0].Exception.StackTrace
    $Error[0].Exception.InnerException.StackTrace
    $Error[0].StackTrace
    
  • Here's a way: Tracing the script stack

    The core of it is this code:

        1..100 | %{ $inv = &{ gv -sc $_ myinvocation }
    

0 comments:

Post a Comment