Getting the current script directory in PowerShell
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.
So that now from my script that requires the (located in the same directory) I can call:
- # Load up our common functions
- $commons = Join-Path (Get-ScriptDirectory) “”;
- . $commons;
Hope this help,