Thursday, March 25, 2010

PowerShell : How to get the script directory

I was looking for a function to get the script directory in a PowerShell script and I didn’t found exaclty found what I was looking for.

I found some scripts on the net that works on PowerShell 1.0 or  2.0 and with Powershell host or PrimalScript 2009 Host (yes I’m using PrimalScript everyday).

So I tooked some code form others and added some of my stuff and here what I came up with :

function get-scriptdirectory {

# .SYNOPSIS 
# 	Return the current script directory path, compatible with PrimalScript 2009
# 	Equivalent to VBscript fso.GetParentFolderName(WScript.ScriptFullName)
# 	Requires PowerShell 2.0
#    
# .DESCRIPTION
#	Author   : Jean-Pierre.Paradis@fsa.ulaval.ca
#	Date     : March 31, 2010
#	Version  : 1.01
#
# .LINK 
# 	http://blog.sapien.com/index.php/2009/09/02/powershell-hosting-and-myinvocation/

    if (Test-Path variable:\hostinvocation) 
    	{$FullPath=$hostinvocation.MyCommand.Path}
    Else {
   		$FullPath=(get-variable myinvocation -scope script).value.Mycommand.Definition }  	
	if (Test-Path $FullPath) {
    	return (Split-Path $FullPath) 
		}
    Else {
		$FullPath=(Get-Location).path
		Write-Warning ("Get-ScriptDirectory: Powershell Host <" + $Host.name + "> may not be compatible with this function, the current directory <" + $FullPath + "> will be used.")
		return $FullPath
		}
}

My function will work on PowerShell command line, PowerShell ISE or PrimalScript 2009. You will, however need PowerShell 2.0.

It is also compatible with a ‘Set-StrictMode -Version 2.0’ (you the thing most best practices guide told you to use).

Update (march 31, 2010) :

Looks like there is currently no way to get the script directory from PowerGUIScriptEditorHost, so I’ve modified my script to return the current directory (and a warning) instead of throwing an error.