Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace square bracket using Powershell

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:

ls  -filter *`[*`]* | foreach -Process { Rename-Item $_ -NewName ($_.Name -replace '\[', '\(') | Rename-Item $_ -NewName ($_.Name -replace '\]', '\)')}

I get the error:

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
like image 394
KalenGi Avatar asked Jan 22 '23 04:01

KalenGi


1 Answers

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/277707/rename-item-fails-when-renaming-a-file-and-the-filename-contains-brackets

https://connect.microsoft.com/PowerShell/feedback/details/553052/rename-item-literalpath

like image 148
Roman Kuzmin Avatar answered Jan 31 '23 14:01

Roman Kuzmin