SharePoint Version History Cleanup Using PowerShell

In a SharePoint document library, we can see the document versions across the site collections. We have a large amount of document versions, some of which will not be required.

The code snippet given below will execute and clean up all the document version's history across the site collections.

Steps
  1. Open your SharePoint Management Shell.
  2. Copy the code given below and paste it.
  3. Run the code given below.
  4. Open your SharePoint site.
  5. Check that the execution completed successfully or not.
Code
  1. $SPsite = new-object Microsoft.SharePoint.SPSite("https://gowtham.sharepoint.com/")  
  2. $website=https://gowtham.sharepoint.com/tutorials/tutorials  
  3. $web = $SPsite.OpenWeb($website)  
  4. foreach ($list in $web.Lists)  
  5. {  
  6.       
  7.     if ($list.BaseType -ne "DocumentLibrary")   
  8.     {  
  9.         continue  
  10.     }  
  11.       
  12.     foreach ($item in $list.Items)  
  13.     {  
  14.         
  15.       $file = $item.File  
  16.       # delete all versions in the document library  
  17.       $file.Versions.DeleteAll()  
  18.     }  
  19. }  
  20. $web.Dispose();  
  21. $site.Dispose();  
  22.   
  23. If you want to delete this one in particular library use this  
  24.   
  25.   
  26. $SPsite = new-object Microsoft.SharePoint.SPSite("https://gowtham.sharepoint.com/")  
  27. $website=https://gowtham.sharepoint.com/tutorials/tutorials  
  28. $web = $SPsite.OpenWeb($website)  
  29. $list="Docuemnts"  
  30. $list = $web.Lists[$list]  
  31. if ($list.BaseType -eq "DocumentLibrary")   
  32. {  
  33.     foreach ($item in $list.Items)  
  34.     {  
  35.         
  36.       $file = $item.File  
  37.       $file.Versions.DeleteAll()  
  38.     }  
  39. }  
  40. $web.Dispose();  
  41. $site.Dispose();   
Thanks for reading this blog.
Ebook Download
View all
Learn
View all