relative path in Import-Module

PowershellPowershell 2.0

Powershell Problem Overview


I have directory structure that looks like this:

C:\TFS\MasterScript\Script1.ps1
C:\TFS\ChildScript\Script2.ps1

What i want to do is specify the relative path in Script2.ps1 to look for Script1.ps1 in the directory hirearchy.

This is what i tried in Script2.ps1:

Import-Module ../MasterScript/Script1.ps1

but it does not work and says it cannot find the module.

If i say Import-Module C:\TFS\MasterScript\Script1.ps1, it works fine. What am i missing here?

Powershell Solutions


Solution 1 - Powershell

When you use a relative path, it is based off the currently location (obtained via Get-Location) and not the location of the script. Try this instead:

$ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
Import-Module $ScriptDir\..\MasterScript\Script.ps1

In PowerShell v3, you can use the automatic variable $PSScriptRoot in scripts to simplify this to:

# PowerShell v3 or higher

#requires -Version 3.0
Import-Module $PSScriptRoot\..\MasterScript\Script.ps1

Solution 2 - Powershell

The new Method for this is $PSScriptRoot

Import-Module $PSScriptRoot\Script1.ps1

Nice little one liner.

Solution 3 - Powershell

This worked for me:

$selfPath = (Get-Item -Path "." -Verbose).FullName
$dllRelativePath = "........"
$dllAbsolutePath = Join-Path $selfPath $dllRelativePath
Import-Module $dllAbsolutePath

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsdfgView Question on Stackoverflow
Solution 1 - PowershellKeith HillView Answer on Stackoverflow
Solution 2 - Powershelluser5780947View Answer on Stackoverflow
Solution 3 - PowershellRok StrnišaView Answer on Stackoverflow