Rename-Item using -Replace with multiple patterns

0

0

Consider the files:

File1 (Custom).jpg
File2(Custom).jpg

I need to rename the files to strip away" (Custom)" and/or "(Custom)" from their Name string (notice the space before the opening parenthesis).

Doing one is easy enough using Rename-Item -NewName {$_.name -replace " \(Custom\)", ""}, but I'd like to do both (and possibly additional string patterns)

I'm having a hard time asking Google the right question, it would seem..

Bjørn H. Sandvik

Posted 2017-10-27T07:51:05.983

Reputation: 199

Look for regular expressions or consider using an easier scheme like taking the first N characters. – Seth – 2017-10-27T08:25:46.500

Answers

0

Read about regular expressions as @Seth suggested. A lot of the time you'll use regular expressions with -match in powershell, but other cmdLets like -replace and select-string also use them.

You already seem to have learned that you need to escape special character like parentheses with a backslash. You can match space characters with \s and specify a quantity of 0 or more matches with *. Next you can use the OR operator which is the pipe charater | to match one of several options (x|y|z) (x or y or z).

"file 1 (fred).jpg" -replace "\s*(\(fred\)|\(barney\)|\(wilma\))", ""
file 1.jpg

"file 2(barney).jpg" -replace "\s*(\(fred\)|\(barney\)|\(wilma\))", ""
file 2.jpg

Clayton

Posted 2017-10-27T07:51:05.983

Reputation: 437