Author Posts

January 5, 2015 at 9:57 pm

Hi Team,
I need help to find the current path of my .psm1 file with in the script. $MyInvocation.mycommand.path is working fine for .ps1 files but not for .psm1
Could someone suggest any other command which works similar to $MyInvocation.mycommand.path for .psm1 files.

January 5, 2015 at 10:01 pm

**EDIT**
And I am trying to use in BEGIN{} block.

ex:

Function Verb-Noun
{
BEGIN
{
SHOULD WRITE HERE
}
PROCESS{}
END{}
}

January 6, 2015 at 5:00 am

Are you running PowerShell 3.0 or later? If so, just use the automatic $PSScriptRoot variable and save yourself some hassle.

If your code needs to support PowerShell 2.0, then what I would do is set a script-scope variable when the module is imported (to $MyInvocation.MyCommand.Path), and then reference that variable from inside your functions. The problem is that $MyInvocation contains different information when you access that variable from inside the function, as opposed to out in the script's scope.

Sample module:

$script:modulePath = $MyInvocation.MyCommand.Path

function Verb-Noun
{
    begin
    {
        Write-Host "Module path: $script:modulePath"
    }
}