Forum Discussion
Powershell script to delete all versions of files in a sharepoint site from all libraries
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()
}
}
- 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 06, 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 ?
- rohankapzFeb 07, 2024Copper Contributor
N51768 I saved around 600GB by running the below script to delete version history from all files but keep the latest 15 versions. It took a few hours but was worth it as we saved so much money on removing excess licenses.
$SiteURL = ""
$NumberOfVersionsToKeep = 15# Credentials
$UserName = ""
$Password = "!"
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)# Connect to SharePoint Online
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Context.Credentials = $Credentials# Specify the document library or folder where you want to remove version history
$LibraryName = "" # Replace with the actual name of your document library# Specify the folder within the library you want to target (optional)
$TargetFolder = "" # Replace with the folder name or path# Get all files in the library or folder along with their versions
$List = $Context.Web.Lists.GetByTitle($LibraryName)
$Context.Load($List)# Define a CAML query to retrieve items based on folder or metadata criteria
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery# Filter by folder (if specified)
if ($TargetFolder) {
$Query.FolderServerRelativeUrl = "/sites/yoursite/$LibraryName/$TargetFolder"
}# You can add additional filters as needed, e.g., by metadata columns
# For example, filtering by a specific metadata column named "Category"
# $Query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Category'/><Value Type='Text'>YourCategoryValue</Value></Eq></Where></Query></View>"$Query.ListItemCollectionPosition = $null
$BatchSize = 100 # Adjust this based on your needs
# Process items in batches
do {
$Items = $List.GetItems($Query)
$Context.Load($Items)
$Context.ExecuteQuery()foreach ($Item in $Items) {
$FileName = $Item["FileLeafRef"]
Write-Host "Processing file: $FileName"# Get all versions of the file
$File = $Item.File
$Versions = $File.Versions
$Context.Load($Versions)$Context.ExecuteQuery()
# Check if there are more versions than the specified limit
if ($Versions.Count -gt $NumberOfVersionsToKeep) {
# Sort versions by version number in descending order
$SortedVersions = $Versions | Sort-Object { [System.Version]::new($_.VersionLabel) } -Descending# Keep the latest 10 versions and delete the rest
foreach ($Version in $SortedVersions | Select-Object -Skip $NumberOfVersionsToKeep) {
Write-Host "Deleting version: $($Version.VersionLabel)"
$Version.DeleteObject()
}$Context.ExecuteQuery()
}
}$Query.ListItemCollectionPosition = $Items.ListItemCollectionPosition
} while ($Query.ListItemCollectionPosition -ne $null)# Disconnect (not needed when using CSOM)
$Context.Dispose()