问题
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
回答1:
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
来源:https://stackoverflow.com/questions/4089028/replace-square-bracket-using-powershell