How to use Test-Path on a directory containing square brackets in the name

Viewed 1796

I have a series of directories that have been created with square brackets in their name. For some inexplicable reason, the Test-Path command returns $false when I run it against these directories, but returns $true if I run the same command against a directory without square brackets in the name.

The directories look like this:

[s]4343224D
[s]50AF43AF

The command I am running is:

Test-Path [s]50AF43AF

I have also tried:

Test-Path `[s`]50AF43AF

But this also returns $false.

Does anyone know how one might get Test-Path to return true when there really is a directory of that name?

2 Answers

You can use the -LiteralPath parameter for this:

Test-Path -LiteralPath '[s]50AF43AF'

Which is probably a better option than adding backticks if you're processing more than one path:

'[s]4343224D','[s]50AF43AF' | ForEach-Object { Test-Path -LiteralPath $_ }

This seems to work:

Test-Path '`[s`]50AF43AF'
Related