You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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-PSCallStack cmdlet时调用的.NET API,普通PowerShell脚本无需直接接触该API,使用内置cmdlet即可完成需求。

内容的提问来源于stack exchange,提问作者iRon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:33:24