Replacing special characters in filenames in Windows powershell

Question:

I am trying to move a bunch of files from a windows directory to a sharepoint, needing to rename file and directory names, that are not allowed on the target filesystem.

Most of what I needed to do the task I found here:
Replacing all # in filenames throughout subfolders in Windows

The solution provided by evilSnobu worked like a charm for these characters ~, #, %, &

The other characters not allowed on sharepoint are supposedly: +, *, {, }, \, :, <, >, ?, /, |, “

I am not exaxtly sure which ones are allowed on the source windows filesystem in the first place, but the “+” is and apparently a lot of filenames have that character in them.

For those I get an error from PowerShell saying that it invalidates the regular expression. This is unfortunately true for using the character or excaping it with the equivalent ascii code.

Unfortunately this does not work. Any idea on how to deal with those?

Thanks Tim

Answer:

From the list that you are not certain of, they are all prohibited except +, {, }. To escape characters in regular expressions, use \, e.g., since $ is the end-of-string anchor regexp, use \$ to match a literal $. Alternatively, instead of $name -replace '+','_', you might consider $name.replace("+","_"), which does not use regexp.

Source:

Replacing special characters in filenames in Windows powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply