views:

490

answers:

4

I want to be able to tell what path my executing script was run from.
This will often not be $pwd. I need to call other scripts that are in a folder structure relative to my script and while I could hard code the paths, that's both distasteful and a bit of a pain in the neck when trying to promote from "dev" to "test" to "production".

Thanks!

+1  A: 

This is one of those oddities (to my mind at least) in PS. I'm sure there is a perfectly good reason for it, but it still seems odd to me. So:

If you are in a script but not in a function then $myInvocation.InvocationName will give you the full path including the script name. If you are in a script and inside a function then $myInvocation.ScriptName will give you the same thing.

EBGreen
JasonMArcher
+4  A: 

I think you can find the path of your running script using

$MyInvocation.MyCommand.Path

Hope it helps !

Cédric

Cédric Rup
That will give you the full path including the script name as long as you are not in a function. If you are in a function then it will be $null.
EBGreen
+2  A: 

I ran into the same issue recently. The following article helped me solve the problem: http://blogs.msdn.com/powershell/archive/2007/06/19/get-scriptdirectory.aspx

If you're not interested in how it works, here's all the code you need per the article:

function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}

And then you get the path by simply doing:

$path = Get-ScriptDirectory
Skyler
+3  A: 

We've been using code like this in most of our scripts for several years with no problems:

#--------------------------------------------------------------------
# Dot source support scripts
#--------------------------------------------------------------------
$ScriptPath = $MyInvocation.MyCommand.Path
$ScriptDir  = Split-Path -Parent $ScriptPath
. $ScriptDir\BuildVars.ps1
. $ScriptDir\LibraryBuildUtils.ps1
. $ScriptDir\BuildReportUtils.ps1
Keith Hill