Forum Discussion
Powershell script to delete all versions of files in a sharepoint site from all libraries
Hi rohankapz,
you can try this script to delete all versions of all files and folders in a SharePoint site but keep the latest 10 versions of each file:
# Import the SharePoint Online Client Library
Import-Module Microsoft.SharePoint.Online.CSOM
# Connect to the SharePoint Online site
$siteUrl = "https://contoso.sharepoint.com/sites/my-site"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
# Get all the web libraries in the site
$web = $ctx.Web
$libraries = $web.Lists
# Iterate through each library and delete all versions of all files and folders
foreach ($library in $libraries) {
# Get all the files in the library
$files = $library.Files
# Iterate through each file and delete all versions
foreach ($file in $files) {
# Get the file's version history
$versionHistory = $file.VersionHistory
# Keep the latest 10 versions and delete the rest
$versionsToDelete = $versionHistory.Where({ $_.VersionLabel -eq "1.0" -or $_.VersionLabel -eq "2.0" -or $_.VersionLabel -eq "3.0" -or $_.VersionLabel -eq "4.0" -or $_.VersionLabel -eq "5.0" -or $_.VersionLabel -eq "6.0" -or $_.VersionLabel -eq "7.0" -or $_.VersionLabel -eq "8.0" -or $_.VersionLabel -eq "9.0" })
foreach ($versionToDelete in $versionsToDelete) {
$versionToDelete.Delete()
}
}
}
# Execute the script
$ctx.ExecuteQuery()​
To use this script, simply change the $siteUrl variable to the URL of your SharePoint Online site. Then, run the script in PowerShell.
This script will delete all versions of all files and folders in the site, except for the latest 10 versions of each file. Be sure to back up your data before running this script.
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.
If the post was useful in other ways, please consider giving it Like.
Kindest regards,
Leon Pavesic
- Greg_from_PondNov 04, 2023Copper Contributor
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?- Nov 04, 2023
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. 🙂
- rohankapzSep 21, 2023Copper Contributor
HiLeonPavesic ,
I am getting script error when using the script. I have all modules installed and has happened when upgrading to Windows Powershell 7.
Import-Module : The specified module 'Microsoft.SharePoint.Online.CSOM' was not loaded because no valid module file was found in any module directory.
At line:2 char:1
+ Import-Module Microsoft.SharePoint.Online.CSOM
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (Microsoft.SharePoint.Online.CSOM:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommandNew-Object : Cannot find type [Microsoft.SharePoint.Client.ClientContext]: verify that the assembly containing this type is loaded.
At line:6 char:8
+ $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommandYou cannot call a method on a null-valued expression.
At line:31 char:1
+ $ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull- LeonPavesicSep 21, 2023Silver Contributor
Hi rohankapz,
To fix the script error you are getting, you need to install the Microsoft SharePoint Online Client Library. You can do this by running the following command in PowerShell:
Install-Module -Name Microsoft.SharePointOnline.CSOM -Force -AllowClobber
Once the module is installed and imported:
Import-Module Microsoft.SharePoint.Online.CSOM
you should be able to run the script without any errors.# Install the Microsoft SharePoint Online Client Library Install-Module -Name Microsoft.SharePointOnline.CSOM -Force -AllowClobber # Import the SharePoint Online Client Library Import-Module Microsoft.SharePoint.Online.CSOM # Connect to the SharePoint Online site $siteUrl = "https://contoso.sharepoint.com/sites/my-site" $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) # Get all the web libraries in the site $web = $ctx.Web $libraries = $web.Lists # Iterate through each library and delete all versions of all files and folders foreach ($library in $libraries) { # Get all the files in the library $files = $library.Files # Iterate through each file and delete all versions foreach ($file in $files) { # Get the file's version history $versionHistory = $file.VersionHistory # Keep the latest 10 versions and delete the rest $versionsToDelete = $versionHistory.Where({ $_.VersionLabel -eq "1.0" -or $_.VersionLabel -eq "2.0" -or $_.VersionLabel -eq "3.0" -or $_.VersionLabel -eq "4.0" -or $_.VersionLabel -eq "5.0" -or $_.VersionLabel -eq "6.0" -or $_.VersionLabel -eq "7.0" -or $_.VersionLabel -eq "8.0" -or $_.VersionLabel -eq "9.0" }) foreach ($versionToDelete in $versionsToDelete) { $versionToDelete.Delete() } } } # Execute the script $ctx.ExecuteQuery()
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.If the post was useful in other ways, please consider giving it Like.
Kindest regards,
Leon Pavesic
- rohankapzSep 21, 2023Copper ContributorI get this error when doing this as an admin on powershell
PS C:\Windows\system32> Install-Module -Name Microsoft.SharePointOnline.CSOM -Force -AllowClobber
PackageManagement\Install-Package : No match was found for the specified search criteria and module name
'Microsoft.SharePointOnline.CSOM'. Try Get-PSRepository to see all available registered module repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.2.5\PSModule.psm1:9711 char:34
+ ... talledPackages = PackageManagement\Install-Package @PSBoundParameters
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Ex
ception
+ FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage