如何使用相对路径调用另一个PowerShell脚本?

t3c*_*b0t 16 powershell relative-path

我有以下目录树:

e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1
e:\powershell\utils\Press any key to continue.ps1
Run Code Online (Sandbox Code Playgroud)

现在我想调用一个名为"按任意键继续.ps1"的脚本,它位于"utils"文件夹中,来自我在"services"文件夹中的脚本.我怎么做?我无法弄清楚相对路径.

我试着这样做:

"$ '.\..\utils\Press any key to continue.ps1'"
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

man*_*lds 31

根据您的工作,以下内容应该有效:

& "..\utils\Press any key to continue.ps1"
Run Code Online (Sandbox Code Playgroud)

要么

. "..\utils\Press any key to continue.ps1"
Run Code Online (Sandbox Code Playgroud)

(查找使用之间的差值&.,并决定要使用哪一个)

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

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

& "$utilsDir\Press any key to continue.ps1"
Run Code Online (Sandbox Code Playgroud)

  • &和的链接.本来不错的.不完全是Google友好的搜索表达式. (43认同)
  • 对于那些仍然有问题试图找到它们之间的差异的人.并查看以下博客:http://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes/ TL; DR"." 调用脚本并在当前作用域"&"调用脚本中运行,并在不同的子作用域中运行并被丢弃 (18认同)
  • 如果其他人想要理解&,它是"Invoke-Expression"的快捷方式 - 请参阅http://technet.microsoft.com/en-us/library/ee176880.aspx (6认同)

Sha*_*evy 9

将以下函数放在调用脚本中以获取其目录路径并将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 
Run Code Online (Sandbox Code Playgroud)


小智 5

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

#mainscript.ps1

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

$Second
Run Code Online (Sandbox Code Playgroud)