我的目录结构如下所示:
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
,它工作正常。我在这里失踪了什么?
当您使用相对路径时,它基于当前位置(通过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
这对我有用:
$selfPath = (Get-Item -Path "." -Verbose).FullName
$dllRelativePath = "........"
$dllAbsolutePath = Join-Path $selfPath $dllRelativePath
Import-Module $dllAbsolutePath
新方法是$PSScriptRoot
Import-Module $PSScriptRoot\Script1.ps1
漂亮的小一个班轮。