【问题标题】:Test-Path fails to return $True on a file that existsTest-Path 无法在存在的文件上返回 $True
【发布时间】:2012-04-26 02:37:40
【问题描述】:

我正在尝试验证文件是否存在,但问题是文件名中包含方括号,即 c:\test[R] 10005404, Failed with Comments, [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

【问题讨论】:

标签: powershell powershell-2.0 powershell-ise


【解决方案1】:

尝试使用 -LiteralPath 参数:

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

方括号有特殊含义。

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

dir [a-f]*

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

【讨论】:

    【解决方案2】:

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

    使用与您的方法类似的方法,您需要在使用双引号时添加 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
    

    【讨论】:

    • +1 当需要在名称中包含[] 的文件或文件夹旁边使用诸如*.txt 之类的通配符时,前两个是理想的解决方案
    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多