Getting PowerShell Script Location at Run Time in PowerShell Command line

55 Views Asked by At

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

There are 1 best solutions below

2
Mathias R. Jessen On BEST ANSWER

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
}