I run a PowerShell script. How do I get the directory path of this script I run?
How to do this?
PowerShell Get Current Directory of Script File To get current directory of script file or running script, use $PSScriptRoot automatic variable.
On Windows, the location of the user-specific CurrentUser scope is the $HOME\Documents\PowerShell\Modules folder. The location of the AllUsers scope is $env:ProgramFiles\PowerShell\Modules . On non-Windows systems, the location of the user-specific CurrentUser scope is the $HOME/. local/share/powershell/Modules folder.
2 or later you can do cd - to navigate to your previous directory. cd is the alias for Set-Location . Adding paramerter + or - goes forward or backward through your location history. +1 This is the best answer for modern users.
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2 $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With