2014-10-08 72 views
4

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

我正在编写的脚本模块是用于从文件相对于导入脚本加载设置。我打算重复使用该模块进行一些项目,所以我宁愿如果该模块不能假定它从哪里导入。

这是一件很棒的事,它会很棒,模块可以尽可能隐含。如果一切都失败了,我可以让呼叫者通过它的位置。

不幸的是,迄今为止我尝试过的一切都会返回模块的路径(而不是导入它的内容)。这里有一个简单的例子:


试验RelativeModule.ps1在储存: C:\测试\

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

试试这个:

Write-Host "My invoker's PSScriptRoot: $($MyInvocation.PSScriptRoot)" 
+0

*太近*! '分裂路径'是不需要的。只是:'写主机'调用者:$($ MyInvocation.PSScriptRoot)“' - 编辑,我会接受。谢谢! – klyd 2014-10-08 21:40:25

+0

我更新了答案。 – 2014-10-08 22:08:39