获取定义PowerShell函数的文件的路径

时间:2013-04-15 01:52:29

标签: powershell powershell-v3.0

我正在试图找到一种方法来获取定义PowerShell 函数的文件路径(例如,Test1或Test2),而不是调用者的路径,这可以通过$PSScriptRoot自动变量轻松获得。

考虑以下文件夹结构:

c:\Scripts\Test.ps1
c:\Scripts\Test1\Test1.ps1
c:\Scripts\Test2\Test2.ps1

Test.ps1

Set-Location $PSScriptRoot;
. .\Test1\Test1.ps1;
. .\Test2\Test2.ps1;

Test1;
Test2;

Test1.ps1

function Test1 {
    [CmdletBinding()]
    param (
    )
    Write-Host -Object "Entering Test1";
    Write-Host -Object "Exiting Test1";
}

Test2.ps1

function Test2 {
    [CmdletBinding()]
    param (
    )
    Write-Host -Object "Test2";
    Write-Host -Object "Exiting Test2";
}

我尝试在$PSCmdlet$MyInvocation自动变量上使用各种属性,但似乎找不到获取定义函数的文件路径的方法,而不是在哪里呼叫者位于。

不同的问题是,当从C:\Scripts\Test1\Test1.ps1调用Test1函数时,如何从Test.ps1函数中获取路径Test2.ps1Test2脚本和C:\Scripts\Test2\Test2.ps1函数也是如此。如何从Test2函数中获取路径.

这是不可能的,因为我正在使用{{1}}调用运算符,将函数导入当前会话?

2 个答案:

答案 0 :(得分:11)

这是另一种方法,使用函数的scriptblock文件属性获取包含该函数的文件:

${function:Test1}.File

答案 1 :(得分:6)

我认为$ PSCommandPath有你想要的东西。