powershellwindows-scripting

Getting PowerShell Script Location at Run Time in PowerShell Command line


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.


Solution

  • 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
    }