PowerShell v3 RC Bug: $MyInvocation.MyCommand.Path is $null in supporting script module files

In PowerShell version 2.0, you could use the $MyInvocation.MyCommand.Path property to detect where a script block was being called from. This was very useful to me, because I would embed test code in the bottom of each of my supporting script files, for a given module.

Here is a sample filesystem structure:

1
2
3
4
5
6
\WindowsPowerShell
   \Modules
      \Test
         \Test.psm1
            \Get-Foo.ps1
            \Set-Bar.ps1

In the Get-Foo.ps1 file, I would probably have a block of code at the bottom of the file, after the Get-Foo function definition, to test the Get-Foo function. Here is what that code block would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Get-Foo {
    [CmdletBinding()]
    param (
          [string] $Param1
        , [int] $Param2
    )
   
    # Do something
}

if ($MyInvocation.MyCommand.Path -match '\.psm1$') {
    Write-Host -Object 'Script is running as part of a module. Skipping tests.';
}
else {
    Write-Host -Object 'Script is NOT running as part of a module. Running tests.';

    # Implement test code here
    Get-Foo -Param1 Value1 -Param2 Value2;
}

In my module file Test.psm1, I would have code to import the supporting script files similar to the following:

1
2
3
4
5
6
7
8
9
10
11
12
$ScriptPath = Split-Path -Path $MyInvocation.MyCommand.Path;
$ScriptList = Get-ChildItem -Path $ScriptPath -Filter *.ps1;

foreach ($Script in $ScriptList) {
    Write-Host -Object "Importing script: $($Script.FullName)";
   
    Invoke-Expression -Command ([IO.File]::ReadAllText($Script.FullName));
   
    # Dot-sourcing the script causes the script file to see its own path as
    # $MyInvocation.MyCommand.Path;
    #. "$($Script.FullName)";
}

Unfortunately, in PowerShell version 3.0, the ability to detect which file invoked another script block is gone. Someone suggested using $PSCommandPath, but the purpose of that variable is different: it’s designed to detect the currently running file, NOT to detect the file that invoked that block of code.

I’ve filed a bug with Microsoft on this problem, and hopefully they will fix it before release:

https://connect.microsoft.com/PowerShell/feedback/details/746643/myinvocation-mycommand-path-is-null-when-importing-a-script-file-from-a-module-file-psm1

Please vote on this issue to help get it fixed!

  • http://twitter.com/pcgeek86/status/210022743222136832/ (@pcgeek86) (@pcgeek86)

    #PowerShell v3 RC bug: $MyInvocation.MyCommand.Path is $null when importing script module file. http://t.co/BpbVH2c4