请参考同级目录中的脚本
在PowerShell中,是否有办法引用位于“同级目录”的脚本——也就是同一父目录下的另一个文件夹中的脚本?
目前我的PowerShell脚本中有这一行:
.\mysuperscript.ps1 -param1 bla -param2 blabla -param3 blob
然而,由于重构,这个脚本已不再与正在执行它的脚本处于同一个目录,而是移到了同一父目录下的另一个文件夹中。
我正在尝试做类似这样的事情,但不确定是否可行。
我知道可以通过脚本来确定位置、拼接路径等,但这似乎更简单。
.\..\siblingfolder\mysuperscript.ps1 -param1 bla -param2 blabla -param3 blob
这样的做法可能吗?
解决方案
使用 ..\ 来引用父目录是有效的语法,使用它来调用你的脚本将可以正常工作,但前提是你的 $PWD(当前目录)与调用该脚本的所在位置相同,示例:
# this script will call script2.ps1 placed in testfolder2 in the parent directory
$item1 = New-Item '.\testfolder1\script1.ps1' -Value { param($a, $b) ..\testfolder2\script2.ps1 -a $a -b $b } -Force
# this script is the one called by script1.ps1 receiving the parameter values `$a` and `$b`
$item2 = New-Item '.\testfolder2\script2.ps1' -Value { param($a, $b) "$a $b" } -Force
Push-Location .\testfolder1
# Works OK, outputs `hello world`
.\script1.ps1 -a hello -b world
Pop-Location
# But calling the script from here fails...
.\testfolder1\script1.ps1 -a foo -b bar
正如你所看到的,上面的示例应该可以工作;然而如果你移除 Push-Location,并将工作目录改到一个不是 testfolder1 的目录,它很可能会失败。
或许有一种在使用相对路径的同时更稳健的处理方式,即以 $PSScriptRoot 作为起点来构造路径,例如:"$PSScriptRoot\..\testfolder2\script2.ps1"(相对于脚本父级位置的路径);然后你可以使用 & 调用 来执行该脚本,并且无论 $PWD 如何都应该工作良好:
# this script will call script2.ps1 placed in testfolder2 in the parent directory
$item1 = New-Item '.\testfolder1\script1.ps1' -Value { param($a, $b) & "$PSScriptRoot\..\testfolder2\script2.ps1" -a $a -b $b } -Force
# this script is the one called by script1.ps1 receiving the parameter values `$a` and `$b`
$item2 = New-Item '.\testfolder2\script2.ps1' -Value { param($a, $b) "$a $b" } -Force
Push-Location .\testfolder1
# Works OK, outputs `hello world`
.\script1.ps1 -a hello -b world
Pop-Location
# Also works OK from here, outputs `foo bar`
.\testfolder1\script1.ps1 -a foo -b bar
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。