Get the Current Location of the PowerShell Script
Split-PathCmdlet to Get the Current Location of the PowerShell Script
$PSScriptRootVariable to Get the Current Location of the PowerShell Script
- Getting the Working Directory in Windows PowerShell to Get the Current Location of the PowerShell Script
Whenever we need to reference a common module or script, we would like to use paths relative to the current script file. That way, the script can always find other scripts in the library.
In this article, we will discuss different ways to get the current location of the running PowerShell script.
Split-Path Cmdlet to Get the Current Location of the PowerShell Script
Before PowerShell 3, there was no better way of querying the
MyInvocation.MyCommand.Definition property by using the
Split-Path -Parent $($global:MyInvocation.MyCommand.Definition)
Split-Path cmdlet is used with the
-Parent parameter to return the current directory of the running script.
It is worth noting that this will only work if you include the syntax above on a saved PowerShell (
.ps1) file. Running the syntax above in the command line will return a
It is also worth noting that running the syntax above in PowerShell’s Integrated Scripting Environment (ISE) as a selection (Run as a Selection or pressing F8) will trigger a
ParameterArgumentValidationErrorNullNotAllowed or a Null exception.
A simple remedy to fix the issue is to call the
$psISE variable and get the
CurrentFile.FullPath property, and from there, you can get the current location of the script. Remember that this syntax is best used when testing in the PowerShell ISE.
$PSScriptRoot Variable to Get the Current Location of the PowerShell Script
If you are running PowerShell version 3 or later, an automatic variable has been introduced to store the current file or module’s directory.
$PSScriptRoot variable returns the value of the directory of the running script.
Getting the Working Directory in Windows PowerShell to Get the Current Location of the PowerShell Script
Now that we have discussed how to get the current location on the script, it wouldn’t hurt to learn to get our script’s current working directory.
In Windows PowerShell v2, the
$ExecutionContext variable contains the
EngineIntrinsics property. You can use this variable and property to find the execution objects available to cmdlets, including the current working directory of the running Windows PowerShell script.
However, if you’re running the latest version of Windows PowerShell, a separate cmdlet has been introduced to make things convenient. We can use the
Get-Location cmdlet and call in the
Path property to get the script’s current working directory.