4

Let's say I have this file:

C:\[foo]\bar

I then run these PowerShell commands:

$path = 'C:\[foo]'
get-childitem -literalpath $path

Everything works fine, get-childitem shows me the file bar, then returns immediately.

Now I add the -recurse option:

$path = 'C:\[foo]'
get-childitem -literalpath $path -recurse

get-childitem no longer displays the file bar. In addition, the cmdlet runs a long time and displays various "permission denied" error messages for folders underneath C:\Windows, apparently because it scans the entire C: drive.

The problem is tied to the fact that the folder [bar] has brackets in the name. If I rename the folder to bar, i.e. without brackets, the result with recursion works as expected.

My main question: How can I convince get-childitem to recursively scan folders that have brackets (or other special characters) in the name?

A secondary question: Is this a known bug?

Environment: Windows 8.1, PowerShell 4.0.


EDIT: I verified that in PowerShell 2.0 (on a Windows 7 machine) get-childitem returns the same result with or without -recurse. It appears that the behaviour has changed either in version 3.0 or 4.0.

herzbube
  • 13,158
  • 9
  • 45
  • 87
  • Reported this as a bug, [see here](https://connect.microsoft.com/PowerShell/feedbackdetail/view/1707779/). Please vote if you think this should be fixed. – herzbube Aug 24 '15 at 15:14

1 Answers1

3

I also get the same results as you on Windows 7 x64 bit with PowerShell 4.0. From the looks of it the recursive functionality is ignoring the -LiteralPath.

This is a workaround put I found a TechNet post discussing the same issue. The OP in that post ended up using -Path and double escaping the brackets.

$path = "C:\[foo]"
$escapedPath = $path.Replace("[","``[").Replace("]","``]")
Get-ChildItem -Path $escapedPath -Recurse

Note: This will fail if you remove the -Recurse

Get-ChildItem : Cannot find path 'C:\`[foo`]' because it does not exist.
Matt
  • 45,022
  • 8
  • 78
  • 119
  • 2
    Although ugly as hell, it does the trick. *sigh* One more hack I need to be aware of when using PowerShell :-( – herzbube Aug 24 '15 at 13:24
  • @herzbube Wait it out. I havent _really_ answered the question yet. Still don't know the real reason for your issue. Someone with more experience than me might know what is going on. – Matt Aug 24 '15 at 13:25
  • Yeah, sure, if someone has a better answer I will consider it, but for the moment I am going with your solution. You know, it's a build script that is failing here, so there is some urgency :-) – herzbube Aug 24 '15 at 13:31