PowerShell for Windows Admins

Jan 21 2015   12:21PM GMT

Awkward file and folder names

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

Spent some time today dealing with a situation where there were special characters – namely [ ] in folder a file names

£> Get-ChildItem -Path C:\Test
Directory: C:\Test
Mode                LastWriteTime     Length Name
—-                ————-     —— —-
d—-        21/01/2015     17:58            Awkward [One]
d—-        21/01/2015     17:59            Simple One

Each folder has 3 files:

File 1.txt
File 2.txt
File 3.txt

Get-ChildItem -Path ‘C:\Test\Simple One’

will work and show you the contents. When I’m typing paths like this I let Tab completion do the work. Type c:\test\ and use the Tab key to cycle round the available folders. This gives

£> Get-ChildItem -Path ‘C:\Test\Awkward `[One`]’
Get-ChildItem : Cannot find path ‘C:\Test\Awkward `[One`]’ because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path ‘C:\Test\Awkward `[One`]’
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (C:\Test\Awkward `[One`]:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Unfortunately, the construct produced by Tab completion doesn’t work. You need to double up on the back ticks so that it functions as an escape character.

Get-ChildItem -Path ‘C:\Test\Awkward “[One“]’

But that only shows you the folder not the contents.

Get-ChildItem -Path ‘C:\Test\Awkward “[One“]\*’

OR

Get-ChildItem -Path ‘C:\Test\Awkward “[One“]’ -Include *

Will show you the contents of the folder.

But bizarrely

Get-Content -Path ‘C:\Test\Awkward `[One`]\File 1.txt’

Works. As does

Copy-Item -Path ‘C:\Test\Awkward `[One`]\File 1.txt’ -Destination c:\test2

By using back ticks and quotes you can get round most problems like this. Other characters that cause similar problems are commas and quote marks.

Best advice of all – don’t use those awkward characters in your file names if you can possibly avoid it.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: