【问题标题】:How do I call another PowerShell script with a relative path?如何使用相对路径调用另一个 PowerShell 脚本?
【发布时间】:2011-11-14 17:35:11
【问题描述】:

我有以下目录树:

e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1
e:\powershell\utils\Press any key to continue.ps1

现在我想从我在“services”文件夹中的脚本中调用一个名为“Press any key to continue.ps1”的脚本,该脚本位于“utils”文件夹中。我怎么做?我无法弄清楚相对路径。

我试着这样做:

"$ '.\..\utils\Press any key to continue.ps1'"

但它不起作用。

【问题讨论】:

标签: powershell relative-path


【解决方案1】:

根据您所做的,以下应该有效:

& "..\utils\Press any key to continue.ps1"

. "..\utils\Press any key to continue.ps1"

(查找 the difference between using & and . 并决定使用哪一个)

这就是我处理这种情况的方式(与@Shay 提到的略有不同):

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$utilsDir  = Join-Path -Path $scriptDir -ChildPath ..\utils

& "$utilsDir\Press any key to continue.ps1"

【讨论】:

【解决方案2】:

要获取当前脚本路径,可以使用 $PSScriptRoot 变量。例如 以下是结构: 解决方案\mainscript.ps1 解决方案\secondscriptfolder\secondscript.ps1

#mainscript.ps1

$Second = Join-Path $PSScriptRoot '\secondscriptfolder\secondscript.ps1'

$Second

【讨论】:

    【解决方案3】:

    将以下函数放入调用脚本中以获取其目录路径并与脚本名称一起加入 utils 路径:

    # create this function in the calling script
    function Get-ScriptDirectory { Split-Path $MyInvocation.ScriptName }
    
    # generate the path to the script in the utils directory:
    $script = Join-Path (Get-ScriptDirectory) 'utils\Press any key to continue.ps1'
    
    # execute the script
    & $script 
    

    【讨论】:

    • 这个解决方案有两个问题:第一个 - 这不是我想要实现的,因为“ulits”目录不是“服务”的子目录,我必须离开“服务”和然后输入“utils”来调用正确的脚本。 2nd - ScriptName-Property 为空。我已经编辑了这个问题,所以它更清楚了。
    • 这真的取决于控制台工作目录(在控制台中输入 pwd)。如果您想使用相对路径,您需要先 cd 进入源脚本目录,然后使用 ..\folder\script.ps1。您确定 Get-ScriptDirectory 不返回调用脚本的父文件夹吗?
    • 我的错。我必须监督 Get-ScriptDirectory 函数确实有效。
    • 使用 Get-ScriptDirectory 很可能不会返回你认为应该的;这一切都取决于你如何称呼它。我在对How can I find the source path of an executing script? 的回答中就这一特定点进行了大量撰写,然后将其扩展为 Simple-Talk.com 上的一篇文章:Further Down the Rabbit Hole: PowerShell Modules and Encapsulation
    【解决方案4】:

    非常感谢您提供的信息。 我有类似的问题,我可以让它像这样工作,从父文件夹调用其他脚本。

    $CommandPath = (Get-Location).Path | Split-Path -Parent; $script = "$CommandPath\Logins\Login_SSI_SST_exch2010_DKSUND_Exchange365.ps1"; & $script
    

    【讨论】:

      猜你喜欢
      • 2013-11-14
      • 2015-07-07
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      相关资源
      最近更新 更多