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.
$mypath = $MyInvocation.MyCommand.Path Write-Output "Path of the script : $mypath"
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.
$ScriptName = $MyInvocation.MyCommand.Name Write-Output "`nName of the script : $scriptname"
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,