Luis
Luis

Reputation: 3033

Properly referencing scripts in PowerShell

I'm a newbie in PowerShell and I'm having some problems when defining some utility scripts that are "included" in other files; the problem is regarding paths. Let me explain the issue with a simple example:

Imagine you have some utility script named utility.ps1 located under /tools and you want to invoke it from a build.ps1 placed under /build. Now imagine that the utility.ps1 invokes some other utility script in the same folder called "utility2.ps1". So,

utility.ps1:

[...]
.".\utility2.ps1"
[...]

build.ps1:

[...]
."..\tools\utility.ps1"
[...]

The problem here is that when calling from build to utility.ps1 and then from this last one to utility2.ps1, powershell is trying to load utility2.ps1 from the current dir (build) instead of the tools dir.

My current workaround is pushd . before calling and popd after that but it smells bad, I know; on the other hand if some day I move scripts to some other location I'd need to update all my scripts that use the moved one... a mess.

So, I'm doing something very wrong; what would be the proper one to do this, making the client script unaware and independant of the "utility" script location?

Upvotes: 2

Views: 215

Answers (1)

Aman Sharma
Aman Sharma

Reputation: 1990

The answer by PetSerAl in the comments is perfect but will work for PowerShell 3+. If for some reason you want your script to be backward compatible as well, then use the below code snippet to find the $ScriptRootPath (which is automatically populated via $PSScriptRoot for PS 3+)

$ScriptRootPath = Split-Path $MyInvocation.MyCommand.Path -Parent

For PS 3+, populate this variable via the global variable:

$ScriptRootPath = $PSScriptRoot 

and then use the solution as described by PetSerAl,
i.e. for utility.ps1: . "$ScriptRootPath\utility2.ps1"
for build.ps1: . "$ScriptRootPath\..\tools\utility.ps1"

Also refer this question on SO

Upvotes: 3

Related Questions