How to Get the Current Location of the PowerShell Script

  1. Using the Split-Path Cmdlet to Get the Current Location of the PowerShell Script
  2. Using the $PSScriptRoot Variable to Get the Current Location of the PowerShell Script
  3. Getting the Working Directory in Windows PowerShell to Get the Current Location of the PowerShell Script
  4. Conclusion
How to Get the Current Location of the PowerShell Script

In this comprehensive guide, we delve into various methods to determine the current location of a PowerShell script, a fundamental aspect that enhances script portability and reliability. Each method discussed caters to different versions of PowerShell and scripting scenarios, ensuring wide applicability.

We begin with the Split-Path cmdlet, a versatile approach for earlier PowerShell versions, then transition to the convenience of $PSScriptRoot in PowerShell 3 and later. Further, we explore the robust $ExecutionContext method and the straightforward Get-Location cmdlet, catering to diverse environments and requirements.

Finally, we simplify the process with the familiar pwd alias, showcasing PowerShell’s adaptability.

Using the 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 cmdlet.

The primary purpose of using Split-Path with $global:MyInvocation is to extract the directory path of the currently executing PowerShell script. This is especially useful when scripts need to interact with other files or directories in the same location as the script or when the script’s behavior depends on its location.

$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition
Write-Host "Current script location: $scriptDirectory"

In this example, we are using Split-Path with the -Parent parameter to isolate the directory component from the full path of the running script. This path is obtained from $MyInvocation.MyCommand.Definition.

The resulting directory path is stored in the variable $scriptDirectory.

Finally, we use Write-Host to output this directory path, providing a clear and immediate view of the script’s current location. This method is not only efficient but also ensures compatibility across different versions of PowerShell.

Output:

get the current location of the powershell script - output 1

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 Null exception.

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.

Using the $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.

The $PSScriptRoot variable holds the directory path of the script being executed. This automatic variable is incredibly useful for creating portable scripts where hard-coding paths are not practical.

It’s especially handy when your scripts need to load files or modules that are located in the same directory as the script itself.

Write-Host "The current script is located in: $PSScriptRoot"

In our script, we use the Write-Host cmdlet to print the value of $PSScriptRoot. This variable automatically contains the full path to the directory where the script is located.

By invoking Write-Host, we ensure that the path is displayed in the PowerShell console. This approach is both easy and effective, making the script versatile for various environments and scenarios.

Output:

get the current location of the powershell script - output 2

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.

$currentScriptLocation = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.\')
Write-Host "Current script location: $currentScriptLocation"

In this example, we utilize $ExecutionContext to acquire the current script’s location. By calling the GetUnresolvedProviderPathFromPSPath method with the parameter '.\', we effectively ask PowerShell to translate the current directory (represented by '.\') into a full path.

The result is stored in the variable $currentScriptLocation, which we then display using Write-Host. This method is particularly robust, as it does not rely on the script being run in a specific way and works across different versions of PowerShell.

Output:

get the current location of the powershell script - output 3

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.

$currentDirectory = (Get-Location).Path
Write-Host "Current directory: $currentDirectory"

In the provided code, we first use the Get-Location cmdlet to retrieve the current location object. We then access its Path property to get the current directory as a string, which we store in the $currentDirectory variable.

Finally, we use Write-Host to display this information. This method is highly effective for scripts that need to know their execution context in terms of directory location.

Output:

get the current location of the powershell script - output 4

In PowerShell, pwd is an alias for the Get-Location cmdlet. The Get-Location cmdlet retrieves the current working directory of the PowerShell session, which is exactly what the traditional pwd (print working directory) command does in Unix-like systems.

PowerShell, with its flexibility and compatibility in mind, provides these aliases to make it easier for users who are familiar with other shell environments (like Unix or Linux) to use similar commands in PowerShell.

$currentDirectory = pwd
Write-Host "Current directory: $currentDirectory"

In this example, we use the pwd command to get the current location object, which is then stored in the $currentDirectory variable. By leveraging Write-Host, we output the path of the current directory to the console.

This method is notably straightforward and does not require any complex syntax or additional parameters. It’s a quick and reliable way to ascertain the directory from which the script is being run.

Output:

get the current location of the powershell script - output 5

Conclusion

This article has provided a thorough exploration of various methods to ascertain the current location of a PowerShell script, each tailored to different PowerShell versions and scripting contexts. From the Split-Path cmdlet suitable for earlier versions to the automatic $PSScriptRoot variable in later versions, the guide ensures relevance for a broad range of PowerShell users.

Additionally, the use of $ExecutionContext and the Get-Location cmdlet offer robust and straightforward alternatives, respectively, while the pwd alias presents a familiar option for users from different scripting backgrounds. This comprehensive guide not only enhances script portability and reliability but also underscores PowerShell’s versatile nature.

Armed with these techniques, script writers and system administrators are better equipped to handle file path dependencies, making their scripts more adaptable and effective in various environments. Ultimately, understanding these methods is fundamental in mastering PowerShell scripting and optimizing the functionality of scripts across different platforms and scenarios.

Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn