use*_*721 9 powershell powershell-ise powershell-2.0
我试图验证文件的存在,但问题是文件名在名称中有括号,即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.
Run Code Online (Sandbox Code Playgroud)
$a = $a.Replace("[", "`[")
$a = $a.Replace("]", "`]")
$Result = (Test-Path $a)
# Also returns $False even though the file exists.
Run Code Online (Sandbox Code Playgroud)
想法将不胜感激.谢谢,ChrisM
And*_*ndi 23
尝试使用-LiteralPath参数:
Test-Path -LiteralPath 'C:\[My Folder]'
Run Code Online (Sandbox Code Playgroud)
方括号有特殊含义.
它实际上是一个POSIX功能,所以你可以这样做:
dir [a-f]*
Run Code Online (Sandbox Code Playgroud)
这将为您提供当前目录中以字母A到F开头的所有内容.Bash具有相同的功能.
至少有三种方法可以让它发挥作用.
使用类似于你的方法的东西,你需要在使用双引号时添加2个反引号,因为在发送到Replace方法之前,单个反引号将被评估为转义字符.
$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt"
$a = $a.Replace("[", "``[")
$a = $a.Replace("]", "``]")
$Result = Test-Path $a
Run Code Online (Sandbox Code Playgroud)
在Replace方法中使用单引号也可以防止反引号被删除.
$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt"
$a = $a.Replace('[', '`[')
$a = $a.Replace(']', '`]')
$Result = Test-Path $a
Run Code Online (Sandbox Code Playgroud)
最后,您可以使用LiteralPath不使用通配符的 参数(PowerShell匹配使用方括号来定义可以匹配的一组字符).
$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt"
$Result = Test-Path -LiteralPath $a
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13709 次 |
| 最近记录: |