从模块中获取导入脚本的路径?

时间:2014-10-08 13:11:38

标签: powershell powershell-v4.0

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

我写的脚本模块旨在从相对于导入脚本的文件加载设置。我打算重复使用该模块进行多个项目,所以我更希望模块不会假设它从哪里导入。

这是一个很好的,模块可能会尽可能隐含。如果其他所有方法都失败了,我可以在其位置调用传递函数。

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


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

1 个答案:

答案 0 :(得分:4)

试试这个:

Write-Host "My invoker's PSScriptRoot: $($MyInvocation.PSScriptRoot)"
相关问题