Search code examples
powershellfile-rename

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


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?


Solution

  • 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)