PowerShell: Delete All Old Versions from SharePoint Document Libraries
How many versions of a typical document do you need to keep? 5? 10? 100?
SharePoint content databases often get cluttered with redundant versions of the same documents. In some cases, I’ve seen presentation libraries with less than 10 GB of active content, but hundreds of GBs of content due to gradual changes.
If you’re ready to clear out old versions, SharePoint’s Management Shell makes it easy. The script below will iterate through all lists and update them to keep only the last 2 copies. It will also loop through and delete unneeded versions.
Get–SPWebApplication | Get–SPSite –Limit All | Get–SPWeb –Limit All | ForEach–Object { ForEach ($list in $_.Lists) { If ($list.EnableVersioning –eq $true){ $list.MajorVersionLimit=2; $list.Update(); ForEach ($item in $list.Items){ $item.URL; $item.SystemUpdate() } } } }
You can see that it…
- Loops through all web applications
- Loops through their site collections
- Loops through their webs
- Loops through their lists
- If versioning is enabled, it sets the major version limit to 2
- In order to remove old versions, it needs to loop through each item and perform a system update
The script can be easily amended to deal with only specific site collections / libraries. To keep a different number of versions, modify the MajorVersionLimit variable above.