In the last part, we talked about how to figure out the path to your script, or where in the filesystem your script is located. We saw that when a script starts running, a variable $myInvocation gets created and that this variable has information on how the script was invoked as well as a link to the ScriptInfo. The ScriptInfo has information on the path to the script.
PS>’$myInvocation’ > foo.ps1
PS>$a = .\foo.ps1
PS>$a.mycommand | fl *Path : C:\Temp\foo.ps1
Definition : C:\Temp\foo.ps1
Visibility : Public
Name : foo.ps1
CommandType : ExternalScript
It’s very common to want to access resources relative to the location of your script, e.g. you expect foo.xml to be in the same directory as foo.ps1. By using split-path we can figure out the directory where foo.ps1 is located.
PS>’split-path $myInvocation.mycommand.path’ > foo.ps1
PS>.\foo.ps1
C:\Temp
Then we can use join-path to create the path to new files we expect in the same directory. Here is a script that creates a new path for ‘LibraryScript.ps1′ which should be in the same directory as the script we are running.
PS>type foo.ps1
$myDirectory = split-path $myInvocation.mycommand.path
$myLibraryScript = join-path $myDirectory ‘LibraryScript.ps1′$myLibraryScript
PS>.\foo.ps1
C:\Temp\LibraryScript.ps1
Once we have the path in the variable, it’s really easy to invoke the script via dot sourcing or ‘&’ as needed. Note that we need to do this in the script and not in a function contained in a script as the function will have it’s own $myInvocation variable which has the CommandInfo for the function, not the script. I constantly find myself adding those lines I just showed you and setting up the paths to all the helper scripts and data files needed by my script.