Home Dashboard Directory Help
Search

$MyInvocation.MyCommand.Path is null when importing a script file from a module file (.psm1) by Trevor Sullivan


Status: 

Active


19
0
Sign in
to vote
Type: Bug
ID: 746643
Opened: 6/5/2012 6:31:52 AM
Access Restriction: Public
2
Workaround(s)
view
6
User(s) can reproduce this bug

Description

In my PowerShell module file (.psm1), I am referencing (importing) supporting script files with the code below. In PowerShell version 2.0, in the supporting script file, $MyInvocation.MyCommand.Path is set to the path of the .psm1 file. However in PowerShell version 3, it is $null.

I use this property very extensively to implement test code in the bottom of each of my supporting script files. That way, the test code does not run when the module is imported, but I can still execute the individual script files and test the code inside of them.

Details
Sign in to post a comment.
Posted by Trevor Sullivan on 6/7/2012 at 7:50 AM
Ignore the previous comment -- an environmental issue on one system was causing "PowerShell.exe -version 2.0" to actually launch PowerShell v3, as confirmed by running:

$host.Runspace.Version.Major;

The original bug report still stands, though there are two potential work-arounds, both found by Shay Levy.
Posted by Trevor Sullivan on 6/6/2012 at 8:38 AM
Running powershell.exe -version 2.0 doesn't help either; it exhibits the same behavior. That seems to defeat the purpose of having the -version parameter on the PowerShell executable, doesn't it?
Posted by Trevor Sullivan on 6/5/2012 at 10:14 AM
@qa_warrior: That won't work. First off, MyCommand is $null, and secondly, the Definition property of either the FunctionInfo or CmdletInfo class will simply retrieve the actual definition of the entity.

http://msdn.microsoft.com/en-us/library/system.management.automation.cmdletinfo.definition(v=vs.85)
http://msdn.microsoft.com/en-us/library/system.management.automation.functioninfo.definition(v=vs.85)

Posted by qa_warrior on 6/5/2012 at 9:59 AM
Try this $MyInvocation.MyCommand.Definition
Sign in to post a workaround.
Posted by Shay Levi on 6/7/2012 at 7:51 AM
You can get the path to the psm1 file with:

$ExecutionContext.SessionState.Module.Path
Posted by Trevor Sullivan on 6/7/2012 at 5:56 AM
This alternative seems to work, however two questions:

1. How can I be sure that the caller will *always* be index #1 from the Get-PSCallStack results?
2. Why is the behavior of $MyInvocation.MyCommand broken between PowerShell v2 and v3?

(Get-PSCallStack)[1].ScriptName
File Name Submitted By Submitted On File Size  
Test Module.zip 6/5/2012 713 bytes
Test.zip 6/6/2012 1 KB