powershell:如何在发生错误时打印总调用堆栈?

Dan*_* Wu 5 powershell

假设我有以下代码,当错误发生时,我想看到错误首先发生在函数b,然后发生在函数a.但实际上它只告诉我错误发生在函数a,因为函数a可以多次调用,我不知道哪个外函数调用函数导致问题

cls  
function a{  
  Remove-Item "not-exist-item"  
}  
function b{  
  a  
}  
b  
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 5

如果您使用的是PowerShell v2.0,请使用Get-PSCallStack.如果你还在v1上,请使用如下函数:

function Get-CallStack {
    trap { continue }
    1..100 | foreach {
        $var = Get-Variable -scope $_ MyInvocation
        $var.Value.PositionMessage -replace "`n"
    }
}
Run Code Online (Sandbox Code Playgroud)


Rom*_*min 5

一种选择是设置

$ErrorActionPreference = 'inquire'
Run Code Online (Sandbox Code Playgroud)

然后调用有问题的脚本。出错时提示您进行选择,选择Suspend进入嵌套提示模式。然后输入

Get-PSCallStack
Run Code Online (Sandbox Code Playgroud)

甚至

Get-PSCallStack | fl
Run Code Online (Sandbox Code Playgroud)

获取当前调用堆栈信息。