2014-10-08 63 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