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:

[cc]
\WindowsPowerShell
\Modules
\Test
\Test.psm1
\Get-Foo.ps1
\Set-Bar.ps1
[/cc]

In the [cci]Get-Foo.ps1[/cci] 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:

[cc lines=”-1″ lang=”powershell”]
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;
}
[/cc]

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

[cc lang=”powershell”]
$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)”;
}
[/cc]

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!