This is one of my most used snippits of code. I generally put this at the beginning of every script. Every time I need it, I always say I need to post this as a powerbit so that I can find it more easily. Well, my wait is finally over, and you get the pleasant side effect of learning my most used trick.
The following bit of code will populate $currdir. If the script is run via a .ps1 file, it will set $currdir to be the directory where the .ps1 file lives. This will allow you to right click on a file and say “run with powershelll”, and have it use the files in that directory. The problem with this is that it will notwork if you are developing in ISE or in a powershell.exe host window. In that scenario, you generally want $currdir set to the directory your shell is in. This snippit will do just that, i.e., if it is not run via .ps1 file, it will load from $pwd (with some regex to strip out the psprovider nonesense).
$currdir = '' if ($MyInvocation.MyCommand.Path) { $currdir = Split-Path $MyInvocation.MyCommand.Path } else { $currdir = $pwd -replace '^\S+::','' }
You can fork or clone this gist off of github here, or just run the following:
git clone https://gist.github.com/6715996.git
