To Know Current Path

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of  Anonymous 1 year, 11 months ago.

  • Author
    Posts
  • #21649
    Profile photo of
    Anonymous

    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.

  • #21650
    Profile photo of
    Anonymous

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

    ex:

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

  • #21661
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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"
        }
    }
    
  • #21665
    Profile photo of
    Anonymous

    Thnx Wyatt.

You must be logged in to reply to this topic.