当路径有特殊字符时,包含脚本不起作用
Including a script does not work when path has special characters
我正在尝试使用点语法将脚本包含在同一文件夹中的另一个脚本中:
. '.\BaseScript.ps1'
脚本路径中有一个名称中带有方括号的文件夹。即使我使用的是相对路径,还是出现路径错误
将其移动到名称中没有特殊字符的其他路径可以正常工作。
使用相对路径如何解决这种情况?
解决这个问题的方法似乎是使用第二个脚本的完整路径:
. (Join-Path -Path $PSScriptRoot -ChildPath 'SecondScript.ps1')
不幸的是,PowerShell 将操作数视为 .
dot-sourcing and &
call operators (which includes implicit invocation[1] ) as wildcard expressions,这导致包含 [=14= 的路径出现 问题],这是一个通配符元字符.
解决方法是将转义[
为`[
;例如,点源路径为 ./test[1]/script.ps1
:
的脚本
# Note: '/' and '\' can be used interchangeably in PowerShell.
. ./test`[1]/script.ps1
重要:如果路径是相对路径,则必须以 ./
或 .\
开头(完整路径见下文)。
注:[
是通配符metacharacter,因为可以用它来表示字符范围([a-z]
) 或套 ([56]
);虽然 ]
显然也是需要的,但转义 [
.
就足够了
这个不幸的要求,也影响到其他上下文,是 GitHub issue #4726 的主题。
或者 - 奇怪的是 - 因为 ,不需要这种转义 如果你使用完整路径 .
# Dot-source 'script.ps1` from the same location as the running
# script ($PSScriptRoot).
# (Use $PWD to refer to the *currrent* dir.)
# Because this results in a *full* path, there is no need to escape, strangely.
. $PSScriptRoot/script.ps1
[1] &
,它可以调用任何命令并在子范围内运行用 PowerShell 代码编写的命令,并不是调用所必需的;例如& ./path/to/script.ps1
和 ./path/to/script.ps1
是等价的;但是,如果路径 被引用 and/or 包含 变量引用 - 请参阅 ,则 &
是必需的。
@Theo 有一个有用的解决方法,但原因是 []
必须在路径中转义。
$path = 'C:\path\`[to`]\script.ps1'
我正在尝试使用点语法将脚本包含在同一文件夹中的另一个脚本中:
. '.\BaseScript.ps1'
脚本路径中有一个名称中带有方括号的文件夹。即使我使用的是相对路径,还是出现路径错误
将其移动到名称中没有特殊字符的其他路径可以正常工作。
使用相对路径如何解决这种情况?
解决这个问题的方法似乎是使用第二个脚本的完整路径:
. (Join-Path -Path $PSScriptRoot -ChildPath 'SecondScript.ps1')
不幸的是,PowerShell 将操作数视为 .
dot-sourcing and &
call operators (which includes implicit invocation[1] ) as wildcard expressions,这导致包含 [=14= 的路径出现 问题],这是一个通配符元字符.
解决方法是将转义[
为`[
;例如,点源路径为 ./test[1]/script.ps1
:
# Note: '/' and '\' can be used interchangeably in PowerShell.
. ./test`[1]/script.ps1
重要:如果路径是相对路径,则必须以 ./
或 .\
开头(完整路径见下文)。
注:[
是通配符metacharacter,因为可以用它来表示字符范围([a-z]
) 或套 ([56]
);虽然 ]
显然也是需要的,但转义 [
.
这个不幸的要求,也影响到其他上下文,是 GitHub issue #4726 的主题。
或者 - 奇怪的是 - 因为
# Dot-source 'script.ps1` from the same location as the running
# script ($PSScriptRoot).
# (Use $PWD to refer to the *currrent* dir.)
# Because this results in a *full* path, there is no need to escape, strangely.
. $PSScriptRoot/script.ps1
[1] &
,它可以调用任何命令并在子范围内运行用 PowerShell 代码编写的命令,并不是调用所必需的;例如& ./path/to/script.ps1
和 ./path/to/script.ps1
是等价的;但是,如果路径 被引用 and/or 包含 变量引用 - 请参阅 &
是必需的。
@Theo 有一个有用的解决方法,但原因是 []
必须在路径中转义。
$path = 'C:\path\`[to`]\script.ps1'