Automating the world one-liner at a time…
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.ps1ScriptLineNumber : 1OffsetInLine : -2147483648ScriptName :Line : .\first.ps1PositionMessage : At line:1 char:11 + .\first.ps1 <<<<InvocationName : .\first.ps1PipelineLength : 1PipelinePosition : 1
***** Second MYINVOCATION *****MyCommand : second.ps1ScriptLineNumber : 3OffsetInLine : 13ScriptName : C:\ps\first.ps1Line : .\second.ps1PositionMessage : At C:\ps\first.ps1:3 char:13 + .\second.ps1 <<<<InvocationName : .\second.ps1PipelineLength : 1PipelinePosition : 1
***** Second MYINVOCATION.MyCommand *****Path : C:\ps\second.ps1Definition : C:\ps\second.ps1Name : second.ps1CommandType : 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 ArchitectVisit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShellVisit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
PSMDTAG:CMDLET:UTILITY: Split-Path
I use %~n0 and %~dp0 all the time from batch files and find this very useful.
Especially if you are calling a common logging utility or event log an need to log the name of the script.
Bit surprised this is not standard in version 1?