PowerShell 路径里的方括号:-Path 可能读到另一个文件
文件名里有方括号时,PowerShell 的路径参数可能把它当作通配符,而不是普通字符。尤其要注意:有时命令不会报错,而是匹配到了另一个文件。
下面是一次本机演示。环境为 Windows 11、PowerShell 7.6.7;示例只操作新建的本机临时目录,不访问云资源或网络。将整段复制到 PowerShell 7 中运行:
$ErrorActionPreference = 'Stop'
$root = Join-Path ([IO.Path]::GetTempPath()) ('ps-path-demo-' + [guid]::NewGuid().ToString('N'))
$literal = Join-Path $root '[demo].txt'
$other = Join-Path $root 'd.txt'
[void][IO.Directory]::CreateDirectory($root)
try {
[IO.File]::WriteAllText($literal, 'literal content')
"Test-Path -Path: $(Test-Path -Path $literal)"
"Test-Path -LiteralPath: $(Test-Path -LiteralPath $literal)"
[IO.File]::WriteAllText($other, 'different content')
"Test-Path -Path(加入 d.txt 后): $(Test-Path -Path $literal)"
"Get-Item -Path: $((Get-Item -Path $literal).Name)"
"Get-Item -LiteralPath: $((Get-Item -LiteralPath $literal).Name)"
"Get-Content -Path: $(Get-Content -Path $literal)"
"Get-Content -LiteralPath: $(Get-Content -LiteralPath $literal)"
if ((Test-Path -LiteralPath $literal) -ne $true -or
(Get-Item -Path $literal).Name -cne 'd.txt' -or
(Get-Item -LiteralPath $literal).Name -cne '[demo].txt' -or
(Get-Content -Path $literal) -cne 'different content' -or
(Get-Content -LiteralPath $literal) -cne 'literal content') {
throw '示例结果与预期不同'
}
}
finally {
[IO.Directory]::Delete($root, $true)
}
实测输出:
Test-Path -Path: False
Test-Path -LiteralPath: True
Test-Path -Path(加入 d.txt 后): True
Get-Item -Path: d.txt
Get-Item -LiteralPath: [demo].txt
Get-Content -Path: different content
Get-Content -LiteralPath: literal content
[demo] 在通配符表达式中表示匹配其中的一个字符,所以 d.txt 符合这个模式。初始目录中只有 [demo].txt,Test-Path -Path 返回 False;加入 d.txt 后,同一个检查返回 True,但 Get-Item -Path 和 Get-Content -Path 实际处理的是 d.txt。
这里也有个容易误判的细节:在这个版本里,当只有 [demo].txt 而没有其他匹配文件时,Get-Item -Path 仍可能找到字面名称。因此不能简单断言“带方括号时 -Path 一定找不到文件”。关键是有多个候选文件时要确认命中了谁。
如果变量已经保存了确切文件名,优先对支持该参数的命令使用 -LiteralPath,让路径按字面处理。若本来就是要按模式批量查找,则使用 -Path,并先检查匹配结果。上面的 finally 只删除示例自己创建的随机临时目录;不要将相同删除逻辑直接套用到现有目录。
参考:Microsoft Learn 的 PowerShell about_Wildcards 和 Get-Item 文档。
本文由 AI 助手协助编写,示例已在上述环境运行核对;没有使用真实用户文件或云资源。
- 点赞
- 收藏
- 关注作者
评论(0)