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

如何从PowerShell清单模块内部深层确定调用脚本?

获取PowerShell模块中调用脚本的路径

要在DoWork.psm1的Do-WorkPart1 cmdlet里输出调用它的script.ps1路径,可采用以下几种实用方法:

方法1:过滤调用栈定位外部脚本

借助Get-PSCallStack获取完整调用栈,过滤掉模块自身的栈帧,提取第一个外部脚本:

function Do-WorkPart1 {
    $callerScript = Get-PSCallStack | Where-Object { $_.ScriptName -ne $MyInvocation.MyCommand.ScriptBlock.File } | Select-Object -First 1
    if ($callerScript) {
        Write-Host "调用脚本路径:$($callerScript.ScriptName)"
    }
}

说明:ScriptName属性对应脚本文件的完整路径,通过排除模块自身文件,精准定位到发起调用的script.ps1。

方法2:直接读取调用栈指定帧

如果模块内没有多层嵌套调用,可直接读取调用栈的第二个帧(跳过当前cmdlet的栈帧):

function Do-WorkPart1 {
    $callerFrame = (Get-PSCallStack)[1]
    if ($callerFrame.ScriptName -and $callerFrame.ScriptName -notlike "*DoWork.psm1*") {
        Write-Host "调用脚本:$($callerFrame.ScriptName)"
    }
}

注意:若模块内存在多层函数调用,需调整索引值或增加过滤条件。

方法3:逐层遍历调用来源

针对模块内嵌套调用的复杂场景,通过逐层遍历$MyInvocation属性,找到外部调用脚本:

function Do-WorkPart1 {
    $currentInvocation = $MyInvocation
    while ($currentInvocation.CommandOrigin -eq 'Internal') {
        $currentInvocation = $currentInvocation.MyCommand.Module.PrivateData['MyInvocation']
    }
    Write-Host "调用脚本:$($currentInvocation.ScriptName)"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:03:10