4

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

Get-ChildItem -Filter "*`#*" -Recurse |
Rename-Item -NewName {$_.name -replace '#','No.' } -Verbose

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.

Get-ChildItem -Filter "*`+*" -Recurse |
>> Rename-Item -NewName {$_.name -replace '+','_' } -Verbose

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

Thanks Tim

TIM
  • 315
  • 4
  • 14
  • Possible duplicate of [How to strip illegal characters before trying to save filenames?](https://stackoverflow.com/questions/23066783/how-to-strip-illegal-characters-before-trying-to-save-filenames) – Andy Sep 27 '18 at 01:42

3 Answers3

9

My current way of cleaning file names/paths is to do this:

$Path.Split([IO.Path]::GetInvalidFileNameChars()) -join '_'

This uses the .NET function for current OS invalid characters (since .NET now runs on more than just Windows). It will replace any invalid characters with _.

hsimah
  • 1,265
  • 2
  • 20
  • 37
3

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.

Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33
  • escaping the "+" worked like a charm, thanks so much. Get-ChildItem -Filter "*`+*" -Recurse | >> Rename-Item -NewName {$_.name -replace '\+','_' } -Verbose – TIM May 10 '18 at 18:31
1
Rename-Item -NewName {$_.name -replace '\+','_' } -Verbose  

So marvelous to solve my problem when I wanna reduced my "filename (1)" to "filename".
I simply modify the script to:

Rename-Item -NewName {$_.name -replace '\(1\)','' } -Verbose

It does really tackle the troublesome manual labor.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68