When renaming a file with PowerShell, how do I handle filenames with “[”?

匆匆过客 提交于 2019-11-26 23:38:04

问题


I'm running this PowerShell command:

Get-ChildItem .\tx\*.htm | Rename-Item -NewName {$_.Name -replace '\.htm','.tmp'}

and receive the following error when a filename contains square brackets -- [ and/or ] --, understandable since those have a meaning within the PowerShell syntax.

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

All the other files in the path have similar names (Phrase_With_Underscores.htm), and are renamed without incident. Anyone have any experience with this and know how to counter it so I can manipulate these files?


回答1:


You can workaround using move-item for renaming items using the parameter -LiteralPath.

Is a know bug: Connect (read Keith Hill Comment for: powershell V3 fix this issue)



来源:https://stackoverflow.com/questions/14259317/when-renaming-a-file-with-powershell-how-do-i-handle-filenames-with

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