Powershell

How to Get the Current Directory of the Cmdlet Being Executed

While working in PowerShell, we sometimes need to get the current working directory. This operation helps in referring to a script. More specifically, PowerShell has specific commands that can be used to get the current directory where the cmdlet is being executed. For instance, “Get-Location” is the major command that can be utilized for the discussed purpose.

This post will cover several methods to resolve the mentioned query.

How to Get/Retrieve the Current Directory/Folder of the Cmdlet Being Executed?

These are the approaches that can be used to get the current directory of the command being executed, such as:

Method 1: Getting the Current Directory of the Cmdlet Being Executed Using “Get-Location” Command

The first method that we will utilize to obtain the current directory of the command being executed is the “Get-Location” cmdlet. The current working directory can be retrieved in PowerShell, execute the given command:

> Get-Location

Method 2: Getting the Current Directory of the Cmdlet Being Executed Using “Print Working Directory (pwd)” Command

The “Print Working Directory” or “($pwd)” is used to output the current working directory in PowerShell. The “$pwd” is an alias of the “Get-Location” command.

The current working directory can be retrieved in PowerShell by executing the below-given command:

> $pwd

Method 3: Getting the Current Directory of the Cmdlet Being Executed Using “System Environment” Command

This “[System.Environment]::CurrentDirectory” command is utilized to get or retrieve the fully qualified path of the current working directory:

> [System.Environment]::CurrentDirectory

Method 4: Getting the Current Directory of the Script Being Executed Using “PSScriptRoot” Variable

The “$PSScriptRoot” is a variable cmdlet that can be used to get the current location of the script being executed:

> $PSScriptRoot

That was all about getting the directory in which the cmdlet is currently running.

Conclusion

The current directory/path of the command getting executed in PowerShell can be retrieved using various commands. These commands include “Get-Location”, “$pwd”, “[System.Environment]::CurrentDirectory” commands, or the “$PSScriptRoot” variable value. This post has demonstrated several practical ways to get the current working directory of the cmdlet being executed in PowerShell.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.