【发布时间】:2019-04-26 14:22:37
【问题描述】:
当您在文件名中包含类似 [1] 的内容时,如 File[1].txt 与 Invoke-WebRequest 和 -OutFile 参数一起使用时,您会收到错误 Cannot perform operation because the wildcard path File[1].txt did not resolve to a file.
这是由here 记录的行为引起的。
对于其他 cmdlet,您可以使用 -LiteralPath 强制按字面意思执行路径,但在这种情况下,这不是一个选项。
我尝试使用 ` 或 \ 转义 [ 和 ] 字符,但仍然出现相同的错误。
为了简化测试,您可以使用Out-File、Test-Path 等重现相同的问题。
#Fails
Out-File -FilePath "file[1].txt"
Out-File -FilePath "file`[1`].txt"
Out-File -FilePath "file\[1\].txt"
#Succeeds
Out-File -LiteralPath "file[1].txt"
#Fails
Test-Path -Path "file[1].txt"
#Succeeds
Test-Path -LiteralPath "file[1].txt"
如何对-Path、-FilePath、-OutFile 等中用于表示通配符的字符进行转义,以便它们像-LiteralPath 指定的字符串一样起作用,因为-LiteralPath 不是可通过Invoke-WebRequest获得?
【问题讨论】:
-
在文件周围使用单引号并用反引号转义方括号:
Test-Path -Path 'file`[1`].txt'
标签: powershell escaping glob