removing special characters from entire directory structure

1

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!

l--''''''---------''''''''''''

Posted 2013-04-03T21:03:22.787

Reputation: 713

Answers

1

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.

zdan

Posted 2013-04-03T21:03:22.787

Reputation: 2 732