通过 #Requires -Module加载模块时,无法通过$MyInvocation检索启动脚本的路径或名称



我正在尝试找出一种通用方法,以便在导入模块时获取脚本的名称和路径。 我有三个担忧,我一直无法弄清楚如何使主要问题发挥作用。 这是我的"测试"代码:

测试.ps1

#Requires -Version 5.0
#Requires -Module @{ModuleName='ModuleTest';RequiredVersion='1.0'}
#---remove module to retest the above line
# Remove-Module -Name ModuleTest -Force
#---uncomment and remove requires to test import
#Import-Module -Name ModuleTest -Force
write-host 'Done...'

ModuleTest.psm1 - 保存在模块路径中,通过$env:PSModulePath导入

#Requires -Version 5.0
write-host "callstack = $((Get-PSCallStack).Command -join '; ')"
write-host "ScriptName = $($MyInvocation.ScriptName)"
write-host "PSScriptRoot = $($MyInvocation.PSScriptRoot)"
write-host "PSCommandPath = $($MyInvocation.PSCommandPath)"
write-host "Location = $((Get-Location).path)"
function xyz{...}
function abc{...}

1( 从命令提示符导入模块,调用堆栈返回<ScriptBlock>

callstack = ModuleGroup.psm1; <ScriptBlock>
ScriptName = 
PSScriptRoot = 
PSCommandPath = 
Location = D:Powershell
Done...

2( 使用导入模块的脚本返回完整的MyIn调用信息

callstack = ModuleTest.psm1; Test.ps1
ScriptName = **D:PowershellpsModulesModuleTest1.0TestsTest.ps1**
PSScriptRoot = D:PowershellpsModulesModuleTest1.0Tests
PSCommandPath = D:PowershellpsModulesModuleTest1.0TestsTest.ps1
Location = D:Powershell
Done...

3( 使用 #Requires -Module 语句不返回有关调用方的信息。 (在测试之间删除模块(

callstack = ModuleTest.psm1
ScriptName = 
PSScriptRoot = 
PSCommandPath = 
Location = D:Powershell
Done...

我一直在搜索和测试,尝试范围和$script/$global,以及我能想到的一切。 我更喜欢模块代码检索值,而不是传递它们的脚本,这样我就不必每次都想引用模块时都注意。

如果没有别的,我不会允许 #Requires,并在MyInvocation中没有任何内容时抛出错误。

$MyInvocation变量仅在调用脚本、函数和脚本块后设置。因此,使用命令提示符时不会设置变量。要求语句不应影响这一点。

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-6#myinvocation

最新更新