June 29, 2012

Proper script inclusion in PowerShell

It is handy to use simple script inclusion in PowerShell called dot sourcing:
. .\include.ps1
There is a problem however. If you try to call the script from another directory that script lives in, an error occurs. include.ps1 will not be found since PowerShell uses current folder by default as a starting point.
To avoid this, script directory can be used:
$scriptDirectory = Split-Path -parent $MyInvocation.MyCommand.Definition
. $scriptDirectory\include.ps1

UPD: In newer versions script directory variable is provided on the shelf, just use $PsScriptPath variable

No comments:

Post a Comment