Share via


MyInvocation.MyCommand problems

Question

Friday, October 26, 2012 9:11 AM

If I write a script Test1.ps which has following 2 lines

$dir = split-path -parent $MyInvocation.MyCommand.Definition

echo $dir

it works fine. but I change it to

function GetPath() {

    $f = split-path -parent $MyInvolcation.MyCommand.Definition

    $f

}

$dir = GetPath

Write-Host $dir

it gets me a blank.

Very Annoying!!!!

val it: unit=()

All replies (5)

Sunday, October 28, 2012 12:07 AM âś…Answered | 3 votes

If you use PowerShell V3 you can use the variable $PSScriptRoot to get the path of the script.

-Raimund


Friday, October 26, 2012 9:42 AM

[cmdletbinding()]
Param()
function GetPath() {
 [cmdletbinding()]
 Param()
    $MyInvocation.MyCommand.Definition
}
getpath
$MyInvocation.MyCommand.Definition

Notice that definition value is changing when in function

if You need path use

$MyInvocation.MyCommand.Path


Friday, October 26, 2012 6:16 PM

I don't understand this code why do yo u have repeated cmdletbindign() and param()? what is their purpose?

val it: unit=()


Friday, October 26, 2012 10:04 PM | 1 vote

I don't understand this code why do yo u have repeated cmdletbindign() and param()? what is their purpose?

val it: unit=()

the first set will apply to the script in which they are contained, the second to the function in which they are contained. A bit redundant perhaps, and not necessary for the purpose. But if run from a .ps1 file it illustrates that the value of "$MyInvocation.MyCommand.Definition" is dependent on where it is invoked from.

Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.


Monday, October 29, 2012 7:24 AM

Hi,

Just checking in to see if the suggestions were helpful. Please let us know if you would like further assistance.

TechNet Subscriber Support

If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback here.

Yan Li

TechNet Community Support