Replace square bracket with Powershell

If you have a file name, such as “Committee of Minutes [October 2010] - hq.doc”, how can you force Powershell to replace the square brackets? The following does not work:

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

I get an error message:

 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 
+4
source share
1 answer

Unfortunately, this is a known PowerShell bug / limitation. A suitable and actually good workaround is to use Move-Item to rename items: it has the -LiteralPath parameter, which is missing from the Rename-Item .

See problem reports:

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

+9
source

All Articles