71

How do I do this in PowerShell. In a batch file I would do: %~d0%~p0

2

4 Answers 4

46

For PowerShell 3.0 users - following works for both modules and script files:

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath
}
Sign up to request clarification or add additional context in comments.

Comments

37

From Get-ScriptDirectory to the Rescue blog entry ...

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

2 Comments

See also the answer at the duplicate: stackoverflow.com/a/6985381/60620
link in answer => 404
17
Split-Path $MyInvocation.MyCommand.Path -Parent

2 Comments

What's $MyInvocation?
@alex $MyInvocation is an automatic variable created by PowerShell. From the docs (linked): Contains information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command.
-14

In powershell 2.0

split-path $pwd

1 Comment

Wroking directory is not the same as scripts directory.