Delete Version History

Copper Contributor

Hello Team,

 

I'm looking for help with deleting the version history of specific files in SharePoint, but retaining the last 10 versions. I can see that I can manually delete the version history, but this is going to be a rather long task for this particular file, or i can delete them all which we don't want. I've found powershell commands which will go through all files in a document library but nothing for a specific file. Does anyone have anything which will do this? 

 

Thank you.

5 Replies

@AMS-DavidJParkes 

Using PowerShell is one approach. Find a PowerShell script that deletes all version apart from x last versions and then add additional constraint for your specific file. It does require coding and some basic testing of course.

Another approach is to use 3rd party Apps that offer this functionality in the browser. i.e. delete all versions and keep x last versions. See example.

 

Hello Paul,

Thank you for your response. I've looked at New-SPOSiteFileVersionBatchDeleteJob, but I cannot run this in my tenant as it is experimental. Is there a command you would recommend i could start with?
You can loop through the Document Versions.count and delete to the number of version you want. if you need some code sample can work on it and share.
Thanks. I'm happy to give it a go, but I'm unsure what command to start with.
If you have list of files in csv and all from same site , we can use below script to delete versions.

# Replace with your own Connect-PnPOnline statement
$SiteUrl = "https://contoso.sharepoint.com/sites/site"
Connect-PnPOnline -Url $SiteUrl -UseWebLogin
# Replace with the path to your own CSV file
$FileList = Import-Csv .\VersionDelete.csv
# Replace with the number of versions you want to keep
$VersionsToKeep = 2
Write-Verbose "Keeping $VersionsToKeep of each file"

foreach($File in $FileList) {
# Remove site from Filename if it's there
$Filename = $File.FileName.Replace($SiteUrl,"")
Write-Verbose "Getting version for file $Filename"

# Get the versions of each file
$FileVersions = Get-PnPFileVersion -Url $Filename
Write-Verbose "Found $($FileVersions.Count) versions"
if ($FileVersions.Count -gt $VersionsToKeep) {

# Pick the ones we want to remove
$DeleteVersionList = ($FileVersions[0..$($FileVersions.Count - $VersionsToKeep)])
Write-Verbose "More than $VersionsToKeep versions. Deleting $($DeleteVersionList.count)"

foreach($VersionToDelete in $DeleteVersionList) {
Write-Verbose "Removing $($VersionToDelete.VersionLabel)"
# Remove the versions
#Remove-PnPFileVersion -Url $Filename -Identity $VersionToDelete.Id -Force
$Output = [PSCustomObject]@{
PSTypeName = 'TKDeletedFileVersion'
Filename = $Filename
DeletedVersion = $($VersionToDelete.VersionLabel)
}
# Output the output
$Output
}
} else {
Write-Verbose "$Filename only had $($FileVersions.Count). Skipping..."
}
}