Test-Path fails to return $True on a file that exists

I am trying to validate the existence of a file but the problem is that the file name has brackets in the name i.e. c:\test[R] 10005404, Failed with Comments, [S] SiteName.txt.

I have tried using the string .replace method with no success.

$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.

Ideas would be greatly appreciated. Thanks, ChrisM


Try using the -LiteralPath parameter:

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

Square brackets have special meaning.

It's actually a POSIX feature so you can do this:

dir [a-f]*

This will give you all things in current directory that start with letter A through F. Bash has the same feature.

There are at least three ways to get it to work.

Using something similar to your approach, you need to add 2 backticks when using double-quotes since a single backtick will be evaluated as an escape character before being sent to the Replace method.

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

Using single quotes in the Replace method will also prevent the backticks from being removed.

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

Finally, you could use the LiteralPath parameter which does not use wildcards (the square brackets are used by PowerShell matches to define a set of characters that can be matched).

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

Need Your Help

Possible to return Json data from C# class library

c# jquery asp.net-mvc json class-library

I am creating a report which requires returning Lists, and Json data to a web page. I'm working with a multi-tiered application. The web project is created using MVC but the heavy lifting is done in

Why does Java return a date in GMT-4.5 when choosing Co-ordinated Universal Time time zone in Windows?

java windows timezone utc

We have seen a strange issue on some Windows XP machines involving the "Co-ordinated Universal Time" time zone. Not all Windows XP machines seem to have it, but on those that do, the following simple