Forum Discussion
Powershell script to delete all versions of files in a sharepoint site from all libraries
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 ?
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 - alibadarApr 19, 2024Copper ContributorProcessing 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 - N51768Feb 07, 2024Copper Contributor
rohankapzThanks ,
script will remove previous Versions and save up space while the retention policy is in operation?
Can't delete a site/Version because of a retention policy
https://learn.microsoft.com/en-us/sharepoint/troubleshoot/sites/compliance-policy-blocking-site-deletion