Question:
If you have a filename such as “Committee minutes [October 2010] – hq.doc”, how do you get Powershell to replace the square brackets? The following doesn’t work:
1 2 |
ls -filter *`[*`]* | foreach -Process { Rename-Item $_ -NewName ($_.Name -replace '\[', '\(') | Rename-Item $_ -NewName ($_.Name -replace '\]', '\)')} |
I get the error:
1 2 3 4 5 6 7 8 |
Rename-Item : Cannot rename because item at 'Committee minutes [October 2010] - hq.doc' does not exist. At line:1 char:53 + ls -filter *`[*`]* | foreach -Process { Rename-Item <<<< $_ -NewName ($_.Name -replace '\[' ]', '\)')} + CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand |
Answer:
Unfortunately this is a known bug/limitation of PowerShell. A suitable and actually not bad workaround is to use Move-Item
for renaming items: it has the -LiteralPath
parameter which is missing in Rename-Item
.
See reported issues:
https://connect.microsoft.com/PowerShell/feedback/details/553052/rename-item-literalpath