How to replace multiple characters (<3) of all the filenames in a folder (and subfolder) using PowerShell

Viewed 121

I am trying to use PowerShell to set a condition that if a file name contains any of the following symbols (#, %, &. +. {, }, ~),then replace those symbols with "_". I want to apply this to all file and folder names(including files within sub-folders).

I have below code, which partially works, as it only works for replacing 2 symbols "(%, &)". If i want to replace more symbols it doesn't work. An error message pops up and only the first symbol ends up being replaced. Is there a way to fix this code?

Get-ChildItem -Recurse | `
   Where-Object {$_.Name -match '&' -or $_.Name -match '%' } | `
     Rename-Item -NewName { $_.Name -replace '&','_' -replace '%','_' }

As i have no experience in coding, i would really appreciate if you provide the entire code that would fix this issue, thank you!

1 Answers

Use a regex character class/set ([...]) to match all characters of interest:

Get-ChildItem -Recurse | Rename-Item -NewName { $_.Name -replace '[#%&+{}~]', '_' }

Note that I've eliminated the Where-Object call, because it isn't necessary to pre-filter the files:
-replace returns the original string if the regex doesn't match, and Rename-Item is an effective no-op if the -NewName argument is the same as the existing file name.

Also, if you end a line with |, you don't also need ` to signal line continuation.

Related