Import-Module中的相对路径

问题描述 投票:28回答:3

我的目录结构如下所示:

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

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

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

Import-Module ../MasterScript/Script1.ps1

但它不起作用,并说它找不到模块。

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

powershell powershell-v2.0
3个回答
60
投票

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

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

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

# PowerShell v3 or higher

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

3
投票

这对我有用:

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

1
投票

新方法是$PSScriptRoot

Import-Module $PSScriptRoot\Script1.ps1

漂亮的小一个班轮。

© www.soinside.com 2019 - 2024. All rights reserved.