使用PowerShell重命名文件时,如何使用"["处理文件名?

dww*_*n66 3 powershell file-rename

我正在运行此PowerShell命令:

Get-ChildItem .\tx\*.htm | Rename-Item -NewName {$_.Name -replace '\.htm','.tmp'}
Run Code Online (Sandbox Code Playgroud)

当文件名包含方括号 - [和/或]- 时,会收到以下错误,这是可以理解的,因为这些在PowerShell语法中有意义.

Rename-Item : Cannot rename because item at
'Microsoft.PowerShell.Core\FileSystem::C:\users\xxxxx\desktop\tx\
Foofoofoofoo_foo_foo_[BAR]_Foofoofoofoo_foofoofoo.htm' does not exist.
At C:\users\xxxxx\desktop\foo002.ps1:59 char:39
+ Get-ChildItem .\tx\*.htm | Rename-Item <<<<  -NewName { $_.Name -replace '\.htm','.tmp' }
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

路径中的所有其他文件具有相似的名称(Phrase_With_Underscores.htm),并且无需重大事件即可重命名.任何人都有这方面的经验,知道如何反击它,以便我可以操纵这些文件?

CB.*_*CB. 7

您可以move-item使用参数重命名项目的解决方法-LiteralPath.

是一个知道错误:连接 (阅读Keith Hill评论:powershell V3修复此问题)

  • 这是PowerShell v1和v2中的已知错误.通过在Rename-Item中添加-LiteralPath参数,已在v3中修复了此问题. (3认同)
  • 一个bug?来自微软?消灭这个念头!:) (2认同)