2

Edited to better explain overall question:

In PowerShell, what is the difference between using $MyInvocation.MyCommand.Path and $PSScriptRoot for acquiring the running script's current root directory, if any?

My research only indicates that the two are basically interchangeable and that one wasn't introduced until PowerShell v3. I have also been told that $MyInvocation.MyCommand.Path, although not pretty/elegant, has some functionality to it that isn't fully supported by $PSScriptRoot.

So the overall question is:

Are there any Pros and/or Cons between these two PowerShell commands? Are there instances in which you'd rather use one over the other?

@Mathias R. Jessen: I can understand how you are quick to judge this question; however, it is NOT a duplicate and is especially NOT a duplicate of the question you have pointed this to, which asks "how do I get the root directory". My question isn't HOW do I get the root directory, it is WHAT is the difference in functionality between these two commands. And seeing as you nor anyone else has come back to review my revisions, I am forced to re-ask this question.

For example:

If I am running this script remotely or I am utilizing Jenkins to invoke the base script and I chose to utilize $PSScriptRoot over $MyInvocation.MyCommand.Path, would there be a problem or would I essentially have the same exact functionality?

If I have no way to determine whether the server I chose to run the script on has PSv3, but my script was written using PSv3, would using $PSScriptRoot cause problems?

Thank you in advance.

Brandon
  • 731
  • 2
  • 12
  • 29
  • 4
    `$PSScriptRoot` was added in PSv3 as an easy way to find the current script's location without having to parse `$MyInvocation`. They're both automatic variables that get assigned at runtime. Use `Get-Help about_Automatic_Variables` at the commandline. – Maximilian Burszley Aug 09 '17 at 19:21
  • `$PSScriptRoot` isn't available in Powershell version 1 and 2. So `MyInvocation.MyCommand.Path` had to be used. – Jason Snell Aug 09 '17 at 19:21
  • 1
    One advantage of `$MyInvocation` is the scope specifier. I'm unsure if `$PSScriptRoot` offers the same level of manipulation. For example, `$MyInvocation` also refers to the current function it gets invoked in, so you can use `$script:MyInvocation` to get script-level information. – Maximilian Burszley Aug 09 '17 at 19:51
  • @TheIncorrigible: Thank you, that is one of the examples/answers I was looking for – Brandon Aug 09 '17 at 19:53
  • @TheIncorrigible1 Scope modifiers work with either variable. – Ansgar Wiechers Aug 10 '17 at 14:10
  • @AnsgarWiechers Functionally, changing the scope of `$PSScriptRoot` won't make a difference, though, unless, perhaps, working with a module. – Maximilian Burszley Aug 10 '17 at 14:19

0 Answers0