Bancam
Bancam

Reputation: 1

Errors with Get-ChildItem and ChDir if the path contains "["

I am a Powershell newbie, trying to run Get-FileHash over a specific folder. I planned to navigate to the folder first but got an error:

PS C:\Users\pjmmc\Documents\Genealogy\Family Tree Files> cd "McNab [A1]"

cd : Cannot find path 'McNab [A1]' because it does not exist.
At line:1 char:1
+ cd "McNab [A1]"
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (McNab [A1]:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

The folder McNab [A1] does exist.

There was also a problem with Get-ChildItem

PS C:\Users\pjmmc\Documents\Genealogy\Family Tree Files> dir "McNab [A1]"
PS C:\Users\pjmmc\Documents\Genealogy\Family Tree Files>

By a process of elimination, I worked out that [ cannot be used by in a path with Get-ChildItem and probably was special to PowerShell.

I am using PowerShell version 5.1. The following code was a test to demonstrate that the offending character was [. I established that the ] character did not cause a problem.

PS C:\Users\pjmmc\Documents\Genealogy\Family Tree Files> mkdir "["

PowerShell replied:

    Directory: C:\Users\pjmmc\Documents\Genealogy\Family Tree Files  
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        15/06/2022   9:46 PM                [

PS C:\Users\pjmmc\Documents\Genealogy\Family Tree Files> get-childitem "["

PowerShell Replied

Get-ChildItem : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: [
At line:1 char:1
+ get-childitem "["
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
    + FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.GetChildItemCommand    

I went back to cmd and got the 8.3 name and all was well. Maybe I could have found that in Powershell, but more interested in getting the job done.

I have a few folders with [ ] in the name. Is there a workaround for [ as a wildcard in Get-Childitem?

Upvotes: 0

Views: 467

Answers (1)

tanstaafl
tanstaafl

Reputation: 190

For this particular case try below... -LiteralPath

Get-ChildItem -LiteralPath "C:\tes[t"

Powershell - Brackets

Interesting GitHub discussion on this issue here.

Path is not parsed correctly if '[' is present in the path #12168

Upvotes: 1

Related Questions