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

24
我有以下目录树:
e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1
e:\powershell\utils\Press any key to continue.ps1
我想调用一个名为“Press any key to continue.ps1”的脚本,该脚本位于“utils”文件夹中,而我现在要从“services”文件夹中的脚本中调用它。我应该怎么做?我无法弄清相对路径。
我尝试了以下方法:
"$ '.\..\utils\Press any key to continue.ps1'"

但是它没有起作用。


可能是重复问题:https://dev59.com/MWw15IYBdhLWcg3wIYK_(尽管这个问题不特定于相对路径) - Jon Adams
4个回答

52

61
一个连接符 & 和点号 . 会更好。它们不是很适合在谷歌中搜索。 - Christopher Painter
7
如果有其他人想了解"&"符号,它是“Invoke-Expression”的快捷方式-请参见http://technet.microsoft.com/en-us/library/ee176880.aspx。 - Richard J Foster
29
对于那些仍然在试图找到"."和"&"之间区别的人,请看以下博客:http://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes/简而言之,"."调用脚本并在当前作用域中运行,而"&"调用脚本并在不同的子作用域中运行,并被丢弃。 - stanleykylee

12

将下面的函数放在调用脚本中,以获取其目录路径并将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”目录不是“services”的子目录,我必须离开“services”,然后进入“utils”才能调用正确的脚本。第二,ScriptName-Property为空。我已经编辑了问题,使其更清晰。 - t3chb0t
这真的取决于控制台工作目录(在控制台中键入pwd)。如果您想使用相对路径,您需要先cd到源脚本目录,然后使用..\folder\script.ps1。您确定Get-ScriptDirectory不会返回调用脚本的父文件夹吗? - Shay Levy
我的错。我一定是忽视了些东西,Get-ScriptDirectory 函数确实有效。 - t3chb0t
滥用 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 - Michael Sorens

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

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

$Second

1
感谢您提供的信息,非常有用。 我遇到了类似的问题,我通过以下方式解决了它,即从父文件夹调用其他脚本。
$CommandPath = (Get-Location).Path | Split-Path -Parent; $script = "$CommandPath\Logins\Login_SSI_SST_exch2010_DKSUND_Exchange365.ps1"; & $script

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接