11

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

user991721
  • 111
  • 1
  • 1
  • 3
  • There should be quotes around the path name: `$a = 'c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt'`. Is this just a typo, or is it in your code? – Rynant Apr 13 '12 at 18:03
  • An old Windows [PowerShell Tip of the Week](http://technet.microsoft.com/en-us/library/ff730956.aspx) explained why and the workarounds. This is a kind of duplicate question from [powershell get-childitem cannot handle filename starting with [ character even with escape character](http://stackoverflow.com/a/9508802/608772) – JPBlanc Apr 14 '12 at 04:45

2 Answers2

28

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.

Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
5

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
Rynant
  • 23,153
  • 5
  • 57
  • 71
  • +1 First two are ideal solutions when needing to use wildcards like `*.txt` alongside files or folders with `[` or `]` in their names – user66001 Mar 07 '18 at 07:06