relative path in Import-Module

powershell, powershell-2.0

Solution

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

Problem

I have a 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 hierarchy. 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?

Original source