Brackets in file names

If you have brackets – [ or ] – in your file name you can see problems working with the file name. This is how to deal with brackets in file names.

Consider the files:

outdata01.txt
out[data02.txt
out]data03.txt
out]d[ata04.txt

which have a selection of brackets in the file name.

If you try something like

Get-ChildItem -Path c:\test | foreach {Rename-Item -Path $_.Fullname -NewName “New$($_.name)”}

You’ll find that two files

outdata01.txt
out]data03.txt
 

are successfully renamed but the other two fail with an error like

Rename-Item : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not
valid: out[data02.txt

Notice its the two files with left hand brackets that fail.

Its because PowerShell its treating the bracket as the opening of a wildcard / regex pattern.

The easiest way round this problem is to use –Literalpath instead of –Path

Get-ChildItem -Path c:\test | foreach {Rename-Item -LiteralPath $_.Fullname -NewName “New$($_.name)”}

And you’ll find all of the files rename successfully.

LiteralPath treats what ever its given literally – it doesn’t do the interpretation that Path attempts. 

If you think you’re going to have odd characters in your file names then remember to use literalpath – you’ll find it as an alternative on all the core cmdlets that accept paths

This entry was posted in Powershell. Bookmark the permalink.

1 Response to Brackets in file names

  1. Luke says:

    Finally I found a usage for the literal path parameter… Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s