Replace square bracket using Powershell

橙三吉。 提交于 2019-12-19 21:22:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!