Reputation: 315
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
Upvotes: 4
Views: 9886
Reputation: 11
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.
Upvotes: 1
Reputation: 1303
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 _
.
Upvotes: 9
Reputation: 10764
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.
Upvotes: 3