Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

powershell - relative path in Import-Module

I have directory structure that looks like this:

C:TFSMasterScriptScript1.ps1
C:TFSChildScriptScript2.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:TFSMasterScriptScript1.ps1, it works fine. What am i missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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..MasterScriptScript.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..MasterScriptScript.ps1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...