0

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 like this one and a million different results on google and absolutely nothing works how I intend it to. I'm beginning to think that it's impossible to do what I want.

Anyway:

I have a helper function that I put together here. I want to use this as a nice shortcut utility during development.

The problem is that when I call Get-CurrentScriptInfo -All from another script, the values returned are those that correspond to the function I called, not the actual script that called the function. I get it to some extent, the function is the currently running script... but the data is useless to me: I don't need or want that information. I might as well just paste $PSCommandPath and call it a day. But I'm stubborn. And I want this to work. :)

I've tried:

$MyInvocation.MyCommand.Path 
$PSCommandPath
$PSScriptRoot
((Get-Variable MyInvocation -Scope 1).Value).MyCommand.Path
$global:MyInvocation.MyCommand.Path
$script:MyInvocation.MyCommand.Path

Here's a screenshot that may make more sense:

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.

fmotion1
  • 237
  • 4
  • 12

1 Answers1

1

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
zett42
  • 25,437
  • 3
  • 35
  • 72
  • Wow. I'm embarrassed I didn't find out about $PSCmdlet when searching. Thank you very much for the solution, it works perfectly. – fmotion1 Nov 19 '21 at 09:20