导入模块中的相对路径

导入模块中的相对路径

问题描述:

我的目录结构如下所示:

I have directory structure that looks like this:

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

我想要做的是在 Script2.ps1 中指定相对路径,以便在目录hirarchy 中查找 Script1.ps1.

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

这是我在 Script2.ps1 中尝试的:

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.

如果我说Import-Module C:\TFS\MasterScript\Script1.ps1,它工作正常.我在这里错过了什么?

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

当您使用相对路径时,它基于当前位置(通过 Get-Location 获得)而不是脚本的位置.试试这个:

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

在 PowerShell v3 中,您可以在脚本中使用自动变量 $PSScriptRoot 将其简化为:

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