Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing special characters in filenames in Windows powershell

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

like image 806
TIM Avatar asked Dec 14 '22 16:12

TIM


1 Answers

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 _.

like image 177
hsimah Avatar answered May 12 '23 10:05

hsimah