Can I get detailed exception stacktrace in PowerShell?

alex2k8 picture alex2k8 · Apr 28, 2009 · Viewed 50.7k times · Source

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

Answer

Andy Schneider picture Andy Schneider · Apr 28, 2009

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
   }
}