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

user991721 picture user991721 · Apr 13, 2012 · Viewed 14.5k times · Source

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.

Tried

$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

Answer

Andy Arismendi picture Andy Arismendi · Apr 13, 2012

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.