【问题标题】:Including a script does not work when path has special characters当路径包含特殊字符时,包含脚本不起作用
【发布时间】:2021-10-15 00:37:17
【问题描述】:

我正在尝试使用点语法在同一文件夹中的另一个脚本中包含一个脚本:

. '.\BaseScript.ps1'

脚本的路径有一个名称中带有方括号的文件夹。即使我使用的是相对路径,路径错误仍然会出现。

将其移动到名称中没有特殊字符的其他路径可以正常工作。

在使用相对路径时如何处理这种情况?

【问题讨论】:

  • 无法重现(在 PowerShell.exepowershell_ise.exe 5.1.19041.1151 以及 pwsh.exe 7.1.2 中尝试过)并且路径中的方括号的奇怪组合......

标签: powershell scripting


【解决方案1】:

解决这个问题的方法似乎是使用第二个脚本的完整路径:

. (Join-Path -Path $PSScriptRoot -ChildPath 'SecondScript.ps1')

【讨论】:

  • Join-Path -LiteralPath $PSScriptRoot ..., (将路径传递给-Path 将导致通配符通配符)
  • @MathiasR.Jessen Join-Path 没有-LiteralPath 参数..(经过测试且有效)
  • 确实,西奥。 @MathiasR.Jessen,Join-Path 没有 -LiteralPath 参数,因为它需要一个:它纯粹是一个字符串操作,不涉及通配符解析。
【解决方案2】:

不幸的是,PowerShell 将操作数处理为 . dot-sourcing& call 运算符(其中包括 隐式 调用[1] ) as wildcard expressions,这会导致路径包含[ 的问题,这是一个通配符元字符。 p>

解决方案是将[转义`[;例如,点源一个路径为./test[1]/script.ps1的脚本:

# Note: '/' and '\' can be used interchangeably in PowerShell.
. ./test`[1]/script.ps1

重要提示:如果路径是相对的,则必须以./.\ 开头(完整路径见下文)。

注意:[ 是通配符metacharacter,因为您可以使用它来表示字符范围 ([a-z]) 或集合 (@ 987654339@);虽然] 显然也需要,但转义[ 就足够了。

这个不幸的要求,也影响到其他上下文,是GitHub issue #4726 的主题。


另外 - 奇怪的是 - 作为 Theo's helpful answer shows如果你使用完整路径,这种转义的需要就消失了

# 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 是等价的;但是,如果路径被引用和/或包含变量引用,则需要& - 请参阅this answer

【讨论】:

  • 我没有意识到这是由于评估为通配符表达式。 [] 如何在 PowerShell 的通配符表达式中使用?我以为我们仅限于 *? 通配符。
  • 我不知道 PowerShell 中的通配符表达式可以使用类似于 bash 的字符范围。直到,谢谢!
  • 很高兴听到这个消息,@BendertheGreatest。是的,你不经常看到它。请注意,Get-ChildItem-Filter 参数确实支持这些范围,因为它不是 PowerShell 而是文件系统 API 处理表达式。
【解决方案3】:

@Theo 有一个有用的解决方法,但原因是[] 必须在路径中转义。

$path = 'C:\path\`[to`]\script.ps1'

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2021-01-08
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2020-12-25
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多