使用 Powershell 替换方括号
如果您有一个文件名,例如“委员会会议纪要 [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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,这是 PowerShell 的一个已知错误/限制。一个合适且实际上不错的解决方法是使用
Move-Item
重命名项目:它具有-LiteralPath
参数,而Rename-Item
中缺少该参数>。请参阅报告的问题:
https://connect.microsoft.com/PowerShell/feedback /details/553052/rename-item-literalpath
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 inRename-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