Forum Discussion
Powershell script to delete all versions of files in a sharepoint site from all libraries
- 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 ?
- 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()- alibadarApr 20, 2024Copper Contributor
its not finding the files under the folder. there are number of files in the folder.
Processing file: BD
Exception calling "ExecuteQuery" with "0" argument(s): "Cannot invoke method or retrieve property from null object. Object returned by the following call stack is null. "File
""
At C:\Users\mudassar.raza\Desktop\Delete-versionbyfolder.ps1:58 char:1
+ $Context.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServerException
- Greg_from_PondFeb 07, 2024Copper Contributor
Hi,
I would not recommend using a script like this as part of a live/ongoing system. The better solution would be to use a Document Library template for the site, and set the maximum versions to a fairly low number (acceptable to your business). If you have a 3rd party backup, that number can be as low as 5-10 and still provide good protection.
For the retention policy, you can have automated rules in place at folder (or file) level to move or delete files after 7 years.
I tend to have a separate SharePoint site called ARCHIVE, or similar, with restricted access and any files older than the retention period get moved there. That in turn has an auto-delete rule to avoid compliance issues.
This can be achieved fairly easily using tags or labels, standard retention policies or Power Automate flows.
I hope that helpsGreg
NB - that script doesn't work in it's current form. I ended up just moving the files to a separate site and removing the versions at the same time. I saved 800GB overnight,
- Feb 07, 2024
Just a tip but intelligent versioning is comming soon, which should solve the versioning issue:
Edit:
I've created a script that enables Intelligent versioning and applies it to each site, it also starts a job that deletes all versions for all files older than 365 days
How to Free Up Storage in SharePoint Online Using Intelligent Versioning and PowerShell