使用 Powershell 替换方括号

发布于 2024-09-30 15:00:25 字数 731 浏览 1 评论 0原文

如果您有一个文件名,例如“委员会会议纪要 [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏天碎花小短裙 2024-10-07 15:00:25

不幸的是,这是 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 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文