- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
$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,
- How to get the currently logged-in user account with Azure CLI in PowerShell?
- How to validate the path with the PowerShell function parameter?
- How to echo print statements while executing an SQL script?
- 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 test the shared location path from the remote computer in PowerShell?
- How to get supported parameters of the cmdlet in PowerShell?
- How to get the port number of the processes using PowerShell?
- How to get the tags of the availability set using PowerShell?
- How to get the list of all the commands available in the PowerShell?
- How to copy Items to the destination path with the different credentials in PowerShell?
- How to get the system files using the Get-ChildItem in PowerShell?
- How to get all the aliases in PowerShell?
- Get the name of the file and path in Java
- How to get the list of local groups using PowerShell?