4

有没有办法获取从该模块中导入模块的脚本的路径?

我正在编写的脚本模块旨在从与导入脚本相关的文件中加载设置。我计划在多个项目中重用该模块,所以我希望该模块不能对它的导入位置做出任何假设。

这是一个很好的选择,如果模块可以尽可能隐式,那就太好了。如果一切都失败了,我可以让调用者通过它的位置。

不幸的是,到目前为止我所做的一切都返回了模块的路径(而不是导入的路径)。这是一个简单的演示:


Test-RelativeModule.ps1存储在: c:\test\

import-module "$PSScriptRoot\mod\Test.psm1"

Test.psm1存储在: c:\test\mod\

# returns 'c:\test\mod'
write-host "`$PSScriptRoot: $PSScriptRoot"

# returns 'c:\test\mod'
# The value of $MyInvocation.MyCommand.Path is 'c:\test\mod\Test.psm1'
write-host "Split Invoation: $(Split-Path $MyInvocation.MyCommand.Path)"

# returns whatever path the console is currently residing
write-host "Resolve Path: $((resolve-path '.\').path)"

# what I'm looking for is something to return 'c:\test' from within the module
# without making any assumptions about the folder structure
4

1 回答 1

5

试试这个:

Write-Host "My invoker's PSScriptRoot: $($MyInvocation.PSScriptRoot)"
于 2014-10-08T21:09:44.767 回答