2

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?

Luis
  • 2,833
  • 3
  • 27
  • 41
  • Could you please elaborate? I've seen this link: http://stackoverflow.com/questions/6874779/powershell-include-another-script-that-has-includes, but bear in mind that I have some indirect dependencies and I don't know, from any utility script, what value is stored in $PSScriptRoot, so I cannot assume how many steps should I move to the parent directory, etc. – Luis Apr 25 '16 at 16:07
  • 2
    **utility.ps1**: `."$PSScriptRoot\utility2.ps1"`, **build.ps1**: `."$PSScriptRoot\..\tools\utility.ps1"`. – user4003407 Apr 25 '16 at 16:15

1 Answers1

3

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

Community
  • 1
  • 1
Aman Sharma
  • 1,930
  • 1
  • 17
  • 31