Powershell Script to Replace Special Characters in File Name

When you try to upload multiple files in SharePoint using a PowerShell script, you may end up with script not uploading certain files. The reason is the file has the special characters in its name. First you need to remove all the special characters in the file name before uploading it.

The following powershell script is used to replace special characters in file name,

  1. $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm  
  2. $LogFile = ".\ReplaceSpecialCharactersInFileNamePatch-$LogTime.rtf"  
  3. # Add SharePoint PowerShell Snapin  
  4.   
  5. if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {  
  6.     Add-PSSnapin Microsoft.SharePoint.Powershell  
  7. }  
  8. start-transcript $logfile  
  9. $path = read-host "Enter the path"  
  10. $TestPath = test-path $path  
  11. if($TestPath)  
  12. {  
  13.    Get-ChildItem -path $path -recurse |   
  14.    Foreach-Object {   
  15.       $newName = $_.name -replace '[~#%&*{}|:<>?/|"]'''  
  16.       if (-not ($_.name -eq $newname)){  
  17.          Rename-Item -Path $_.fullname -newname ($newName)  
  18.       }  
  19.   }  
  20. }  
  21. else  
  22. {  
  23.    write-host "Invalid path details.... Please run the script again and enter the valid path" -fore cyan  
  24.    write-host "SCRIPT FINISHED" -fore yellow  
  25. }  
  26.   
  27. stop-transcript