How to get the path of the currently executing script in PowerShell?


To get the full path of the script we need to use the $myInvocation command. This is an automatic variable and it is only invoked when the script or the function is executed.

$MyInvocation.MyCommand.Path command is useful to get the full path of the script where it resides while $MyInvocation.MyCommand.Name is useful to get the name of the script. 

Example

$mypath = $MyInvocation.MyCommand.Path
Write-Output "Path of the script : $mypath"

Output

PS C:\WINDOWS\system32> C:\Temp\TestPS.ps1
Path of the script : C:\Temp\TestPS.ps1

Please note that we are running the above script from the System32 directory and the output path is C:\temp. To get the script directory, we can use the Split-Path command. for example,

Split-Path $mypath -Parent

To get the name of the script, use can use the Name property as mentioned earlier. 

Example

$ScriptName = $MyInvocation.MyCommand.Name
Write-Output "`nName of the script : $scriptname"

Output

PS C:\WINDOWS\system32> C:\Temp\TestPS.ps1
Name of the script : TestPS.ps1

When you run the above commands directly from the console, it won’t give any output because $MyInvocation can only produce output when the script is invoked. For example,

Updated on: 01-Nov-2023

32K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements