Search code examples
powershellfilepathidiomsdirname

PowerShell equivalent of “dirname $0” from bash


I've used dirname "$0" which is an idiom to determine the path of the running script in bash, e.g.:

pushd "$(dirname "$0")"
data_dir="$(dirname "$0")/data/"

What's PowerShell equivalent of the above idiom?


Solution

  • Since PowerShell version 3.0, the execution context provides 2 script-scoped automatic variables:

    • $PSCommandPath - the file system path to the executing script, eg. C:\path\to\script.ps1
    • $PSScriptRoot - the immediate parent folder of the script, eg. C:\path\to

    So the equivalent of your last statement would be as follows in PowerShell:

    $dataDir = Join-Path $PSScriptRoot data