Get path to file that defines PowerShell function

powershell, powershell-3.0

Solution

I think $PSCommandPath has what you're looking for.

Problem

I'm trying to figure out a way of getting the file path where a PowerShell function is defined (eg. Test1 or Test2), rather than the caller's path, which would be easily obtained via the `$PSScriptRoot` automatic variable. Consider the following folder structure: ``` 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"; } ``` I have tried using a variety of properties on the `$PSCmdlet` and `$MyInvocation` automatic variables, but cannot seem to find a way to obtain the path to the file where the function is defined, rather than where the caller is located. Asked differently, how would I get the path `C:\Scripts\Test1\Test1.ps1` from inside the `Test1` function, when it's called from `Test.ps1`? The same goes for the `Test2.ps1` script, and `Test2` function. How would I get the path `C:\Scripts\Test2\Test2.ps1` from inside the `Test2` function? Is this not possible because I'm using the `.` call operator, to import the functions into the current session?

Original source