How can a script tell what directory it was run from?

PSMDTAG:FAQ: How can a script determine what directory it was invoked from?
PSMDTAG:FAQ: What is $MyInvocation?
PSMDTAG:FAQ: Why is $MyInvocation.ScriptName empty?

Create 2 scripts (First.PS1 and Second.PS1) to explore what is going on with $MyInvocation and how you can use it to determine what directory a script was invoked from:

PS> cat first.ps1
$myInvocation |Format-List *

PS> cat second.ps1
“***** Second MYINVOCATION *****”
$myInvocation |Format-List *
“***** Second MYINVOCATION.MyCommand *****”
$myInvocation.MyCommand |Format-List *

PS> .\first.ps1

MyCommand        : first.ps1
ScriptLineNumber : 1
OffsetInLine     : -2147483648
ScriptName       :
Line             : .\first.ps1
PositionMessage  :
                   At line:1 char:11
                   + .\first.ps1 <<<<
InvocationName   : .\first.ps1
PipelineLength   : 1
PipelinePosition : 1


***** Second MYINVOCATION *****
MyCommand        : second.ps1
ScriptLineNumber : 3
OffsetInLine     : 13
ScriptName       : C:\ps\first.ps1
Line             : .\second.ps1
PositionMessage  :
                   At C:\ps\first.ps1:3 char:13
                   + .\second.ps1 <<<<
InvocationName   : .\second.ps1
PipelineLength   : 1
PipelinePosition : 1


***** Second MYINVOCATION.MyCommand *****
Path        : C:\ps\second.ps1
Definition  : C:\ps\second.ps1
Name        : second.ps1
CommandType : ExternalScript


When you run First.ps1, you see that ScriptName is empty.  The reason for this is that ScriptName refers to the name of the script that called you (Yes – we probably should have chosen a better name).  Notice that when First.Ps1 calls Second.Ps1, ScriptName is the path to First.PS1.

Now look at $MyInvocation.MyCommand.  The PATH property tells you the full path of the current script.  If you want the directory you do the following:

$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path

Jeffrey Snover [MSFT]
Windows PowerShell Architect
Visit the Windows PowerShell Team blog at:
Visit the Windows PowerShell ScriptCenter at: