使用Powershell替换方括号

时间:2010-11-03 16:04:37

标签: powershell pattern-matching rename

如果您的文件名如“委员会会议记录[2010年10月] - hq.doc”,您如何让Powershell替换方括号?以下不起作用:

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

我收到错误:

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 个答案:

答案 0 :(得分:9)

不幸的是,这是PowerShell的已知错误/限制。一个合适且实际上并不错的解决方法是使用Move-Item来重命名项目:它具有-LiteralPath中缺少的Rename-Item参数。

查看报告的问题:

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