0

I am running a PowerShell script and calling $MyInvocation.PSCommandPath within the script and it returns null.

The script is meant to be run within a PowerShell Console because it has command line parameters as such:

.\Users\MyScripts\myscript.ps1 -file1 .\file1.exe -file2 .\file2.exe

Inside my script is the following lines:

$mypath = $MyInvocation.PSCommandPath
echo $mypath

This echo returns nothing is there a way to get the path of myscript.ps1?

I am expecting the script to run and remember path of the script to execute again after a reboot. I was wondering if this was possible using this automatic variable.

1
  • why don't you try something like $myInvocation.myCommand.path Commented Jun 30, 2023 at 14:15

1 Answer 1

2

Use the dedicated $PSCommandPath automatic variable instead:

echo $PSCommandPath

The $PSCommandPath and $PSScriptRoot auto variables were introduced in Windows PowerShell 3.0, if you need compatibility with PowerShell 2.0, do:

if ($PSVersionTable['PSVersion'].Major -lt 3){
  $scriptPath = $MyInvocation.MyCommand.Path
}
else {
  $scriptPath = $PSCommandPath
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you it worked. Why did the other one not work?
@Wandering I can't remember when the behavior of $MyInvocation changed, but $PSCommandPath and $PSScriptRoot auto variables were introduced in PowerShell 3.0 - so if that's the oldest version you need to support => always use $PSCommandPath/$PSScriptRoot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.