- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
- Related Articles
- How to get the currently logged-in user account with Azure CLI in PowerShell?
- How to echo print statements while executing an SQL script?
- How to validate the path with the PowerShell function parameter?
- How to run a PowerShell script from the command prompt?
- How to get a list of all the fonts currently available for Matplotlib?
- How to Get the Path of a Linux Command?
- How to get supported parameters of the cmdlet in PowerShell?
- How to test the shared location path from the remote computer in PowerShell?
- How to get all the aliases in PowerShell?
- How to use Split-Path command in PowerShell?
- How to copy Items to the destination path with the different\ncredentials in PowerShell?
- How to get the system files using the Get-ChildItem in PowerShell?
- How to get the readonly files using Get-ChildItem in PowerShell?
- How to get the list of all the commands available in the PowerShell?
- How to get the port number of the processes using PowerShell?
