Forum Discussion
Powershell script to delete all versions of files in a sharepoint site from all libraries
LeonPavesic Will this not keep the 10 oldest versions, rather than the newest?
I thought version 1.0 was the oldest, and the highest number was the most recent - or have I misunderstood?
Yes you are correct, from what I can see His script is generate from ChatGPT/Copilot and he hasn't looked through it, which can cause problems as GPT makes things up as it goes sometimes....Which in this case would have been pretty dangerous...
This script should do it for you, change the 5 to how many you want to save:
# This script deletes all but the 5 latest versions of each document in a SharePoint Online library
# Connect to SharePoint Online site
$siteUrl = "https://contoso.sharepoint.com/sites/MySite"
Connect-PnPOnline -Url $siteUrl -Interactive
# Get the library name
$libraryName = "Documents"
# Get all the items in the library
$items = Get-PnPListItem -List $libraryName
# Loop through each item
foreach ($item in $items) {
# Get the file object
$file = $item.File
# Get the versions of the file
$versions = $file.Versions
# Sort the versions by creation date in descending order
$sortedVersions = $versions | Sort-Object -Property Created -Descending
# Skip the first 5 versions and delete the rest
$sortedVersions | Select-Object -Skip 5 | ForEach-Object {
$_.DeleteObject()
}
}
- Greg_from_PondNov 04, 2023Copper ContributorMany thanks. You (and the OP) have saved me a couple of hours of research. We have a customer with over 120,000 files, many of which are 1GB+ InDesign files, some with over 70 versions. They wondered why their SharePoint space ran out. 🙂
- Nov 04, 2023Double check the script on test site before going all out 🙂 it needs to be modified to run through whole tenant, try doing that yourself. If you're not able to, tag me and I'll help you out 🙂
- N51768Feb 07, 2024Copper Contributor
NicolasKheirallah Greg_from_Pond Greg_from_Pond rohankapz
We are continuously adding space to SP Online site, because my SharePoint online is constantly running out of space, we have huge libraries with 1000 GB and 10000 Versions.
looking for best solution for high SharePoint storage Issue. and the best practices to Maintain versions if we want, also.
My Question:
with retention policy in place, therefore versions with retention policy will be deleted old versions and limit 50 versions by the script above. If not, what is the best course of action for my problem?
how to clear versions of existing library files without effecting latest file versions. Also, we have retention policy in place for 7 Years ?