I would like to know whether it is possible to REMOVE special characters recursively in powershell from all files in an entire directory structure?
for example if I have a file called:
my presentation (fix).xlsx
I would like to rename it to:
my presentation fix.xlsx
thank you for your guidance.
the reason we need to do this is we are migrating many files into sharepoint 2010 and sharepoint doesnt like files with special characters!
I haven't tested this code, but I think you probably want something similar to this:
effectively, just loop through the directory (modify the function to be recursive) and then replace any inappropriate (modify the regex for what is appropo) characters and replace them with nothing (effectively strip them out).
May try experimenting with something like this:
Above would fix files like:
my presentation (fix).xlsx
test {ddd}.ps1
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:
If you want to add square brackets, you have to escape them using backslashes:
just keep adding characters between the outer square brackets as needed:
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:Some notes:
-LiteralPath
argument on theren
command is required to be able to replace files with square brackets: [] it is only available in Powershell v3 IIRC.