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
“***** FIRST MYINVOCATION *****”
$myInvocation |Format-List *
.\second.ps1



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



PS> .\first.ps1
***** FIRST MYINVOCATION *****

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


PS>


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:   
http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx


 


PSMDTAG:CMDLET:UTILITY: Split-Path