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.

<snip>

  1. function Get-ScriptDirectory
  2. {
  3. $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  4. Split-Path $Invocation.MyCommand.Path
  5. }

</snip>

So that now from my script that requires the Common-Functions.ps1 (located in the same directory) I can call:

  1. # Load up our common functions
  2. $commons = Join-Path (Get-ScriptDirectory) “Common-Functions.ps1”;
  3. . $commons;

Love,
Reddog.

Advertisements

3 thoughts on “Getting the current script directory in PowerShell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s