PowerShell renaming multiple files, specific part of file name

powershell

I'm attempting to rename multiple files that have filenames ending in the same way. These files are currently:
"Foo Bar (U) (V7.9) (USA).txt"
"Few Ber Doo Ber (U) (V7.9) (USA).txt"
ect

I'm trying to remove the "(U) (V7.9) (USA)" section of the name and replace this section with (USA). These files would then be named:
"Foo Bar (USA).txt"
"Few Ber Doo Ber (USA).txt"

I can't quite get it to work, but here's what I've been trying to no avail:

get-childItem '* (U) (V7.9) (USA).txt' | rename-item -newname { $_.name -replace '(U) (V7.9) (USA)','(USA)' }

Best Answer

Several of the characters you are trying to replace are special characters in regex. They have special, reserved meanings that allow you to create complicated expressions when they are not "escaped." In order to escape them, you simply need to include a backslash infront of the special character. Example:

PS C:\> $string = "(U) (V7.9) (USA)"

#Failure
PS C:\> $string -replace "(U) (V7.9) (USA)", "(USA)"
(U) (V7.9) (USA)

#Success
PS C:\> $string -replace "\(U\) \(V7\.9\) \(USA\)", "(USA)"
(USA)

Here's a Powershell Regex Reference in case you run into similar problems. You may notice that the backtick ` character is used instead of the backslash -- the backtick is the escape character in powershell, but that is not true for all regex handling in .NET (which Powershell is built on). Because of that, you may see both used in regex examples for powershell on the internet.

Related Question