The following command will recursively traverse your directory structure matching and for each file or directory that matches, performs a rename on that file by replacing each of the offending characters with an empty character using the powershell -replace
operator.
Note that you will have to create a regular expression that matches all the regular characters that you wish to filter. To match the example you provide and remove round brackets, the regular expression would be:
$re = "[()]"
If you want to add square brackets, you have to escape them using backslashes:
$re = "[\[\]()]"
just keep adding characters between the outer square brackets as needed:
$re = "[\[\]()!]"
Here's the script, note the bit of dance so that the -replace
operator only acts on the base part of the name at each iteration:
dir -Recurse | ?{$_.Name -match $re} | %{ren -literalpath $_.FullName -newname (join-path (get-item $_.PSPArentPath) $($_.Name -replace $re,""))}
Some notes:
- The
-LiteralPath
argument on the ren
command is required to be able to replace files with square brackets: [] it is only available in Powershell v3 IIRC.
- You may end up with name collisions after the rename, this script does not handle that.