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

Status : 

 


22
0
Sign in
to vote
ID 746643 Comments
Status Active Workarounds
Type Bug Repros 6
Opened 6/5/2012 6:31:52 AM
Access Restriction Public

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.

Sign in to post a comment.
Posted by Trevor Sullivan [MVP] 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 [MVP] 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 [MVP] 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