71

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

4 Answers4

45

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

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath
}
shivam
  • 16,048
  • 3
  • 56
  • 71
CodeMonkeyKing
  • 4,556
  • 1
  • 32
  • 34
37

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

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}
JP Alioto
  • 44,864
  • 6
  • 88
  • 112
16
Split-Path $MyInvocation.MyCommand.Path -Parent
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
  • What's `$MyInvocation`? – alex Feb 14 '20 at 18:38
  • @alex [`$MyInvocation`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7#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.` – Dan Atkinson Jul 17 '20 at 10:22
-14

In powershell 2.0

split-path $pwd

FeLocci
  • 1
  • 1