
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Path of 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,