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?

2
  • Could you please elaborate? I've seen this link: stackoverflow.com/questions/6874779/…, 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. Commented Apr 25, 2016 at 16:07
  • 2
    utility.ps1: ."$PSScriptRoot\utility2.ps1", build.ps1: ."$PSScriptRoot\..\tools\utility.ps1". Commented Apr 25, 2016 at 16:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.