PowerShell for N00bs: Libraries, Paths, and You
One of the scripts a coworker inherited has the following workflow:
1. Set-Location $PathContainingScript
2. & $Script
Why? Because the original author was a believer in libraries. Or, specifically, TheMotherOfAllLibraries.ps1. Divide the library into ones for AD, one for host management, etc, or keeping them all in one huge file, that’s a personal decision. However, making the user change their location to the location of the script is a pretty bad user experience. To start with, it is prone to error – most command are either run by
& command.ext
… if it’s on the $env:PATH, or
$PsProvider:\path\to\command.ext
if it isn’t on the $env:PATH.
Making the user Set-Location is just begging for the user to run .\Do-Something.ps1 | Set-Content output.txt, which litters it into $PsProvider:\path\to (\command.ext)
The other reason is just as simple: the user may want to be in their current location for a reason. Why force it, not when it’s so easy to include it in the script?
In short, there’s really no reason to make the user Set-Location like this.
Here’s how to fix it:
$scriptName = (&{$MyInvocation}).InvocationName;
$baseName = Split-Path -Path $scriptName -Leaf;
$dirName = Split-Path -Path $scriptName -Parent;
Import-Module "$dirName\function_library.psm1";
Or, if you want brevity at the cost of readability:
Import-Module "$(Split-Path -Path (&{$MyInvocation}).InvocationName -Parent)\function_library.psm1";