Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell: how to print the total call stacks when error happen?

Tags:

powershell

suppose I have the following code, when the error happens, I'd like to see the error that the error first happened at function b, and then happened at function a. But in fact it only tells me the error happen at function a, since function a could be called many times, I don't know which outer function calling function a caused the problem

cls  
function a{  
  Remove-Item "not-exist-item"  
}  
function b{  
  a  
}  
b  
Remove-Item : Cannot find path 'C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\not-exis
t-item' because it does not exist.
At C:\Users\Daniel.Wu\AppData\Local\Temp\2\a.ps1:***3 char:14***
+   Remove-Item <<<<  "not-exist-item"  
    + CategoryInfo          : ObjectNotFound: (C:\Program File...\not-exist-item:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
like image 685
Daniel Wu Avatar asked Jan 20 '11 23:01

Daniel Wu


3 Answers

If you are on PowerShell v2.0, use Get-PSCallStack. If you're still on v1, use a function like this:

function Get-CallStack {
    trap { continue }
    1..100 | foreach {
        $var = Get-Variable -scope $_ MyInvocation
        $var.Value.PositionMessage -replace "`n"
    }
}
like image 172
Keith Hill Avatar answered Sep 28 '22 05:09

Keith Hill


One option is to set

$ErrorActionPreference = 'inquire'

and then invoke the problematic script. On error you are prompted for choices, choose Suspend to enter into the nested prompt mode. Then type

Get-PSCallStack

or even

Get-PSCallStack | fl

to get the current call stack information.

like image 29
Roman Kuzmin Avatar answered Sep 28 '22 05:09

Roman Kuzmin


Does get-help about_debuggers provide any illumination?

like image 33
mjolinor Avatar answered Sep 28 '22 05:09

mjolinor