如何在Windows PowerShell 5.1中获取递归函数的调用者信息?
在Windows PowerShell 5.1中获取递归函数的调用者信息及脚本行号
问题描述
我编写了一个递归函数,希望在调试模式下获取调用者信息及ScriptLineNumber。在PowerShell 7中可以通过Get-PSCallStack实现,但不清楚如何在Windows PowerShell 5.1中完成相同功能,且对Get-PSCallStack源码中Context.Debugger.GetCallStack()的实现细节不了解。
PowerShell 7中的实现代码如下:MyScript.ps1
[CmdletBinding()]param() function MyFunction($Depth = 0) { if ($DebugPreference -in 'Stop', 'Continue', 'Inquire') { $Caller = (Get-PSCallStack)[1] Write-Debug "Caller: $($Caller.FunctionName), Line: $($Caller.ScriptLineNumber)" } Write-Host 'Current depth:' $Depth if ($Depth -lt 1) { MyFunction ($Depth + 1) } } MyFunction
运行命令及结果:
.\MyScript.ps1 -Debug DEBUG: Caller: <ScriptBlock>, Line: 11 Current depth: 0 DEBUG: Caller: MyFunction, Line: 8 Current depth: 1
解决方案
在Windows PowerShell 5.1中,你可以直接沿用几乎完全相同的代码逻辑,因为Get-PSCallStack是PowerShell 2.0起就内置的cmdlet,返回的CallStackFrame对象同样包含FunctionName和ScriptLineNumber属性,足以满足需求。
适配后的代码(PS5.1可用)
MyScript.ps1
[CmdletBinding()]param() function MyFunction($Depth = 0) { # 检查调试模式是否启用 if ($DebugPreference -notin 'SilentlyContinue', 'Ignore') { # 获取调用栈,索引1对应当前函数的直接调用者 $Caller = (Get-PSCallStack)[1] Write-Debug "Caller: $($Caller.FunctionName), Line: $($Caller.ScriptLineNumber)" } Write-Host 'Current depth:' $Depth if ($Depth -lt 1) { MyFunction ($Depth + 1) } } MyFunction
运行验证
在Windows PowerShell 5.1中执行以下命令:
.\MyScript.ps1 -Debug
输出结果与PowerShell 7一致:
DEBUG: Caller: <ScriptBlock>, Line: 11 Current depth: 0 DEBUG: Caller: MyFunction, Line: 8 Current depth: 1
补充说明
Get-PSCallStack返回的调用栈数组中,索引0代表当前函数自身,索引1代表直接调用者,以此类推。- 关于你提到的
Context.Debugger.GetCallStack(),这是PowerShell内部实现Get-PSCallStackcmdlet时调用的.NET API,普通PowerShell脚本无需直接接触该API,使用内置cmdlet即可完成需求。
内容的提问来源于stack exchange,提问作者iRon
相关产品推荐
相关产品推荐

