Wednesday, October 17, 2012

PowerShell: Current Script Folder (Call operator, dot source, and path)

There are a few ways to get the current directory of the executing PowerShell script, but the issue I ran into was that some of the ways changed based on how the script was called.  This was the PowerShell line I used previously and what works in the PowerShell ISE very well,

 

$scriptFolder = $myInvocation.InvocationName | Split-Path -parent

and this is the line I use now.

 

$scriptFolder = $myInvocation.MyCommand.Path | Split-Path -parent

 

The subtle difference in the usage of myInvocation is explained in detail in Kirk Munro’s deep dive on the topic, http://poshoholic.com/2008/03/18/powershell-deep-dive-using-myinvocation-and-invoke-expression-to-support-dot-sourcing-and-direct-invocation-in-shared-powershell-scripts/.  Basically, there are 3 ways you can call a PowerShell script using either the call operator (&), a dot source (.), or a path.  The first PowerShell line only works when using the full path.  This makes perfect sense after one realizes what the InvocationName property represents, but it was confusing at first.