10

我正在尝试验证文件的存在,但问题是文件名中包含方括号,即 c:\test[R] 10005404,注释失败,[S] SiteName.txt。

我尝试使用字符串 .replace 方法但没有成功。

$a = c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt
$Result = (Test-Path $a)
# Returns $False even though the file exists.

试过了

$a = $a.Replace("[", "`[")
$a = $a.Replace("]", "`]")

$Result = (Test-Path $a)
# Also returns $False even though the file exists.

想法将不胜感激。谢谢,克里斯M

4

2 回答 2

27

尝试使用 -LiteralPath 参数:

Test-Path -LiteralPath 'C:\[My Folder]'

方括号有特殊含义。

它实际上是一个 POSIX 功能,所以你可以这样做:

dir [a-f]*

这将为您提供当前目录中以字母 A 到 F 开头的所有内容。Bash 具有相同的功能。

于 2012-04-13T18:17:21.497 回答
5

至少有三种方法可以让它工作。

使用与您的方法类似的方法,您需要在使用双引号时添加 2 个反引号,因为单个反引号将在发送到方法之前被评估为转义字符Replace

$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt"
$a = $a.Replace("[", "``[")
$a = $a.Replace("]", "``]")
$Result = Test-Path $a

在方法中使用单引号Replace也将防止反引号被删除。

$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt"
$a = $a.Replace('[', '`[')
$a = $a.Replace(']', '`]')
$Result = Test-Path $a

最后,您可以使用 LiteralPath不使用通配符的参数(PowerShell 匹配使用方括号来定义一组可以匹配的字符)。

$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt"
$Result = Test-Path -LiteralPath $a
于 2012-04-13T18:20:23.633 回答