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

问题描述 投票:0回答:1

我试图找到一个通用的方法来获取模块导入脚本的名称和路径。我有三个问题,我一直无法弄清楚如何使主要工作。这是我的'测试'代码:

Test.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)从命令提示符导入模块,callstack返回<ScriptBlock>

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

2)使用Import-Module的脚本返回完整的MyInvocation信息

callstack = ModuleTest.psm1; Test.ps1
ScriptName = **D:\Powershell\psModules\ModuleTest\1.0\Tests\Test.ps1**
PSScriptRoot = D:\Powershell\psModules\ModuleTest\1.0\Tests
PSCommandPath = D:\Powershell\psModules\ModuleTest\1.0\Tests\Test.ps1
Location = D:\Powershell
Done...

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

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

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

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

powershell
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.