67

I run a PowerShell script. How do I get the directory path of this script I run?

How to do this?

5
  • do you want current working directory of the process? Commented Jul 4, 2013 at 3:09
  • 1
    No , I want to know which directory contain this script . Commented Jul 4, 2013 at 3:20
  • if you know the filename, you can use get-childItem to find its path. stackoverflow.com/questions/8677628/… Commented Jul 4, 2013 at 3:21
  • I use get-childItem to get its path , but the result seems contains too much infomation but not just only the path ... Commented Jul 4, 2013 at 3:28
  • you need to use some filtering. look at the link i posted in my earlier comment. that might be useful. Commented Jul 4, 2013 at 3:34

1 Answer 1

176

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
Sign up to request clarification or add additional context in comments.

9 Comments

Why the down vote? Help me make my answer better. Please provide feedback!
I'm a bit new to powershell, could you expand on $MyInvocation.MyCommand.Definition? I see this in many posts and it seems like a placeholder, but for what?
@monojohnny $MyInvocation isn't available at the console, just inside functions and scripts.
That is probably not obvious to everyone and therefore an insanely important piece of information. Thank you for pointing it out.
@Sinaesthetic It isn't a placeholder. $MyInvocation is a System.Management.Automation.InvocationInfo object representing the context the current code was called in. It has all sorts of metadata attached to it.
A possible 'gotcha', is that if your main script dot-sources scripts on different paths, then $PSScriptRoot will represent the path of the dot-sourced script, whilst that script it executes.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.