Forum Discussion

rohankapz's avatar
rohankapz
Copper Contributor
Sep 21, 2023

Powershell script to delete all versions of files in a sharepoint site from all libraries

Please can I get some help in compiling a powershell script which will delete all versions of all files and folder in a Sharepoint site but keep the latest 10 versions of this file. My Org site space is being burned at a rate of 4GB per day and in a few weeks will run out of space for all Sharepoint sites. We are down to 50GB space now, please can someone help.

  • LeonPavesic's avatar
    LeonPavesic
    Silver Contributor

    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

    • rohankapz's avatar
      rohankapz
      Copper 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.ImportModuleCommand

      New-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.NewObjectCommand

      You cannot call a method on a null-valued expression.
      At line:31 char:1
      + $ctx.ExecuteQuery()
      + ~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      • LeonPavesic's avatar
        LeonPavesic
        Silver 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

    • Greg_from_Pond's avatar
      Greg_from_Pond
      Copper 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?

      • NicolasKheirallah's avatar
        NicolasKheirallah
        MVP

        Greg_from_Pond 

         

        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()
            }
        }

         

Resources