Whenever I need to reference a common module or script, I like to use paths relative to the current script file, that way, my script can always find other scripts in the library.
So, what is the best, standard way of determining the directory of the current script? Currently, I'm doing:
$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
I know in modules (.psm1) you can use $PSScriptRoot
to get this information, but that doesn't get set in regular scripts (i.e. .ps1 files).
What's the canonical way to get the current PowerShell script file's location?
Took me a while to develop something that took the accepted answer and turned it into a robust function.
Not sure about others but I work in an environment with machines on both PowerShell version 2 and 3 so I needed to handle both. The following function offers a graceful fallback:
It also means that the function refers to the Script scope rather than the parent's scope as outlined by Michael Sorens in his blog
For PowerShell 3.0
The function is then:
Very similar to already posted answers, but piping seems more PS-like.
I use the automatic variable $ExecutionContext, it works from PowerShell 2 and later.
You might also consider
split-path -parent $psISE.CurrentFile.Fullpath
if any of the other methods fail. In particular, if you run a file to load a bunch of functions and then execute those functions with-in the ISE shell (or if you run-selected), it seems theGet-Script-Directory
function as above doesn't work.