views:

998

answers:

4

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
+3  A: 

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.

Joey
We should file an enhancement request (if it hasn't already been submitted) to have this added automatically to exceptions.
JasonMArcher
+1  A: 

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
   }
}
Andy Schneider
A: 

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
JasonMArcher
+1  A: 
Jay Bazuzi