Search code examples
powershellrecursionfile-rename

Escaping a parenthesis in Powershell's -Replace parameter not working


I want to rename this file:

Howard -((TV) )RED HEADED LEAGUE.mp4

To this:

Howard - (TV) RED HEADED LEAGUE.mp4

Because the -Replace Powershell command expects regex regular expressions, I did this to rename the files:

Get-ChildItem | Rename-Item -NewName {$_.name -replace '\(\(TV\) \)',' \(TV\) '}

But, outputs this error:

Cannot rename the specified target, because it represents a path or device name.

And escaping the parenthesis with back ticks, as google suggests, outputs no errors but no files are renamed:

Get-ChildItem | Rename-Item -NewName {$_.name -replace '`(`(TV`) `)',' `(TV`) '}

How can I make this work? Thanks.


Solution

  • As mentioned in the comments, the substitution string (second right-hand side argument to -replace) does NOT need escaping!

    The substitute placed in the string verbatim, so the resulting file name in your example becomes Howard - \(TV\) RED HEADED LEAGUE.mp4 - which is why the file system complains, \ is not a valid file name character.

    If you simply do:

    {$_.Name -replace '\(\(TV\) \)',' (TV) '}
    

    ... it'll work :)