One thing to remember when developing PowerShell scripts is that your current value in $PWD is the process’ current directory not the one where the script was stored.
In my desire to break out a few functions into a common file in order to load them “dot-sourced” (so that the functions become global) I realised I needed help!
In comes a new function from the PowerShell Team Blog. It’s going straight into my PowerShell Profile: Get-ScriptDirectory. It does exactly as the name says, it gets the current directory that script is executed from.
- function Get-ScriptDirectory
- $Invocation = (Get-Variable MyInvocation -Scope 1).Value
- Split-Path $Invocation.MyCommand.Path
So that now from my script that requires the Common-Functions.ps1 (located in the same directory) I can call:
- # Load up our common functions
- $commons = Join-Path (Get-ScriptDirectory) “Common-Functions.ps1”;
- . $commons;