jump to navigation

Getting the current script directory in PowerShell June 4, 2008

Posted by reddogaw in PowerShell, Tips.
Tags: , , , ,
trackback

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.

Advertisement

Comments»

1. PowerShell script modularization « Left Lobe Logic - June 10, 2008

[...] Make use of Get-ScriptDirectory function to form relative paths from your current script [...]


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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.