how to convert filenames with special characters t

2019-07-20 01:08发布

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!

3条回答
疯言疯语
2楼-- · 2019-07-20 01:34

I haven't tested this code, but I think you probably want something similar to this:

Function Rename-Files($path)
{
 Get-ChildItem -path $path | 
 Foreach-Object { 
      $newName = $_.name -replace '[^A-Za-z0-9-_ \.\[\]]', ''
      if (-not ($_.name -eq $newname)){
        Rename-Item -Path $_.fullname -newname ($newName) 
      } 
 }
} #end function

Rename-Files -path "C:\somepath"

effectively, just loop through the directory (modify the function to be recursive) and then replace any inappropriate (modify the regex for what is appropo) characters and replace them with nothing (effectively strip them out).

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-20 01:34

May try experimenting with something like this:

gci * | % {$newname = $_.name -replace '\(|\)|{|}'  
           if (-not ($_.name -eq $newname)){
               rename-item $_.name $newname
           }
          }

Above would fix files like:

my presentation (fix).xlsx

test {ddd}.ps1

查看更多
Juvenile、少年°
4楼-- · 2019-07-20 01:40

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.
查看更多
登录 后发表回答