Reputation: 23
I am simply trying to rename files using PowerShell, but the script below does not work when there are brackets:
$old = [regex] '_Jackson\(UK\)_'
$new = [regex] '_Jackson\(US\)_'
get-childitem "K:\CustomerVideos" -include @("*.webm","*.mp4","*.mkv") -recurse | foreach-object { rename-item $_ -newname ( $_.name -creplace $old,$new ) }
Rename-Item : Cannot rename because the target specified represents a path or device name.
It does work when $old and $new do NOT contain brackets so I guess it's an escaping issue, yet I'm already using backslashes… what is wrong? Thank you.
Upvotes: 0
Views: 290
Reputation: 2244
Because regex replacement syntax is greatly simplified (character classes, grouping, backreferences, and so forth are all disabled, because they're only good when matching), including the backslashes only confuses things. Specifically, it leaves both backslash and "escaped" character in the final string. This is because [regex]
objects are not actually usable as the replacement strings, so they have to be auto-converted to strings by way of ToString()
first, which returns the original pattern.
Only ever use strings for the replacement patterns.
Upvotes: 2