Getting The Current Path Of An Executing PowerShell Script
[PowerShell, .NET]
PowerShell is an excellent, cross-platform scripting solution that you can use to automate various tasks in Windows, Linux, and Unix environments. The fact that it has full access to the entire .NET ecosystem is the icing on the cake.
I use it for a bunch of quick scripts and utilities across the various devices I work on.
Recently, from within a script, I needed to know the exact location from which the script was running.
Before going any further, I need to point out a few things
- There are multiple versions of
PowerShell
- The original (
Windows PowerShell
), v1.0 to 5.1 - The successor (cross-platform)
PowerShell
, v7 - 7.6
- The original (
Windows PowerShell
is installed by default with Windows.- You cannot assume PowerShell 7 is installed, given that it is not installed by default.
Therefore, if you have no visibility or control of the target machine, you cannot assume the presence of PowerShell 7
.
My scenario is the latter - I have no control or visibility of the target machine under which the script will be run.
With that out of the way, the way to get the path of the current script is to use the MyInvocation automatic variable.
This returns an InvocationInfo object class, and the property we are interested in is MyCommand, which is an object of type CommandInfo
From this, we can retrieve the Path
property.
# Get the current path
$currentPath = $MyInvocation.MyCommand.Path
# Write the path to console
Write-Host $currentPath
This will print something like this (depending on where you saved it):
C:\Projects\PowerShell\Test.ps1
If you need just the parent folder, you need to do a bit more work.
You will need to use the Split-Path cmdLet to extract what you need, passing it the -Parent
parameter.
$currentPath = (Split-Path -Parent $MyInvocation.MyCommand.Path)
This will print the following:
C:\Projects\PowerShell\
NOTE: You have to save the script file for this to work; otherwise, the Path
parameter will be null
.
TLDR
You can use the MyInvocation
automatic variable to get information about the currently running script.
Happy hacking!