Home > Enterprise >  How to access the path and filename of the currently called and/or executing script - utilizing an i
How to access the path and filename of the currently called and/or executing script - utilizing an i

Time:11-20

Please don't immediately flag this as a duplicate question without reading the rest of this post. It sounds the same as many others, but it's not entirely the same at all.

I've gone through about 10 Stack Overflow threads IncorrectVars

Notice that all of the output points to my module definition and not the currently executed script.

I'm really hoping someone here knows of some kind of workaround or obscure technique that will get around this limitation.

Any kind of help or guidance is greatly appreciated.

CodePudding user response:

Use the $PSCmdlet automatic variable, which is available for advanced functions:

c:\subdir\test1.psm1:

Function Get-MyPath {
    [CmdletBinding()]
    param()
    
    $PSCmdlet.MyInvocation.PSCommandPath  # Output
}

c:\test.ps1:

Import-Module .\subdir\test1.psm1 -Force
"My path: $(Get-MyPath)"

Output:

My path: C:\test.ps1
  • Related