SharePoint Tutorials

How To Delete Version History in SharePoint Online using PnP PowerShell

Learn how to delete version history in SharePoint Online using PnP PowerShell, streamlining your document library and enhancing performance.

Introduction

Version history in SharePoint Online allows users to keep track of changes made to files over time. While versioning can be useful, it can also lead to a bloated document library with multiple versions of files. If you want to clean up and delete the version history of files in SharePoint Online using PowerShell, the SharePoint Patterns and Practices (PnP) PowerShell module provides a convenient way to achieve this. In this article, we will guide you through the process of deleting version history using SharePoint Online PnP PowerShell.

Before we proceed, please ensure that you have the following prerequisites in place:

Uninstall the Legacy SharePoint PowerShell Module

1. Open a PowerShell command prompt with administrative privileges. To do this, right-click on the Start button and select “Windows PowerShell (Admin)” or “Windows PowerShell” if you’re using an older version of Windows.

2. To uninstall the module, use the following command

Uninstall-Module -Name Microsoft.SharePoint.PowerShell
Uninstall-Module -Name Microsoft.OnlineSharePoint.PowerShell

3. Confirm the uninstallation by typing “Y” or “A” when prompted.

4. That’s it! The Legacy SharePoint PowerShell module should now be uninstalled from your system.

Installing the PowerShell 7.0 MSI package

PowerShell 7

To install PowerShell on Windows, use the following links to download the install package from GitHub.

Install Latest SharePoint Online PNP PowerShell

Install the New PnP PowerShell Module by running the command in PowerShell 7.0

Install-Module PnP.PowerShell 

Once you have the prerequisites ready, follow the steps below.

Step 1: Register Azure AD Application and Grant Access to the Tenant

1. Register an Azure AD Application in the Azure portal.

Register-PnPManagementShellAccess

2. Grant appropriate permissions to the registered application to access SharePoint Online.

Step 2: Set up the Delete Version History SharePoint Online PNP PowerShell Script

1. Copy and paste the following script into the editor:

# Parameters: Specify the site URL and the name of the document library
$SiteURL = "https://PatrickDomingues.sharepoint.com/sites/MySite"
$LibraryName = "Document Library Name"

# Function to delete all file versions folder by folder within the specified document library
Function Cleanup-Versions([Microsoft.SharePoint.Client.Folder]$Folder)
{
    # Output the folder currently being processed
    Write-host "Processing Folder:" $Folder.ServerRelativeUrl -ForegroundColor Yellow
    
    # Obtain the folder's URL relative to the site
    $FolderSiteRelativeURL = $Folder.ServerRelativeURL.Replace($Web.ServerRelativeURL, [string]::Empty)

    # Retrieve all files within the folder
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File

    # Loop through each file in the folder
    ForEach ($File in $Files)
    {
        # Fetch the file's version history
        $Versions = Get-PnPProperty -ClientObject $File -Property Versions
        Write-host -ForegroundColor White "`tScanning File:" $File.Name

        # If the file has versions, proceed to delete them
        If ($Versions.Count -gt 0)
        {
            # Delete all versions of the file
            $Versions.DeleteAll()
            Invoke-PnPQuery
            Write-Host -ForegroundColor Green "`t`tPrevious Versions of the File Deleted:" $File.Name
        }
    }

    # Retrieve sub-folders, excluding "Forms" and any hidden folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder | Where {($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))}
    Foreach ($SubFolder in $SubFolders)
    {
        # Recursively call the function on each sub-folder
        Cleanup-Versions -Folder $SubFolder
    }
}

# Establish a connection to SharePoint Online using PnP PowerShell
Connect-PnPOnline -Url $SiteURL -Interactive
$Web = Get-PnPWeb

# Access the root folder of the specified document library
$RootFolder = Get-PnPList -Identity $LibraryName -Includes RootFolder | Select -ExpandProperty RootFolder

# Start the version cleanup process from the root folder
Cleanup-Versions -Folder $RootFolder

Step 3: Customize the SharePoint Online PNP PowerShell Script

  • Replace the $SiteURL variable value with the URL of your SharePoint site where the document library is located.
  • Replace the $LibraryName variable value with the name of your document library.

Step 4: Execute the SharePoint Online PNP PowerShell Script

  • Save the script with a .ps1 extension (e.g., SharePointDeleteVersionHistory.ps1).
  • Open PowerShell and navigate to the folder where the script is saved.
  • Run the script by executing the command .\SharePointDeleteVersionHistory.ps1.

The script will connect to the specified SharePoint Online site, traverse through the document library, and delete the version history for each file. It will also recursively clean up version history in sub-folders, excluding the “Forms” folder and hidden folders.

Please note that executing the script will permanently delete all previous versions of files in the specified document library. Make sure to double-check the site URL and document library name before running the script.

In conclusion, using SharePoint Online PnP PowerShell, you can easily delete version history and optimize your document library’s storage. This allows you to keep your SharePoint environment clean and organized, improving overall performance and user experience.

I hope this article was helpful!  You can find more here: SharePoint Articles.


Discover more from Patrick Domingues

Subscribe to get the latest posts sent to your email.

author avatar
Patrick Domingues

21 Comments

  1. Hey there! Came across your post on the WordPress feed and couldn’t resist saying hello. I’m already hooked and eagerly anticipating more captivating posts. Can’t seem to find the follow button, haha! Guess I’ll have to bookmark your blog instead. But rest assured, I’ll be eagerly watching for your updates!

    Thanks – TheDogGod

  2. ————–
    Wow, this is exactly what I’ve been looking for! Thank you so much for sharing this helpful information. I can’t wait to try out these steps and streamline my SharePoint Online version history. Great post!

  3. Nice!!

    Is there a way of doing this so you can select an individual folder?

    I keep getting disconnected with a 429 error so cant get through the entire library in one go without being throttled.

    1. Hello, Yes, I noticed that too. I got throttled as well but not disconnected, it took 1 whole day to go through 3tb of data. You might be able to combat the throttle by adding some sort of timer before jumping to the next file.
      I think there is a way to select a root folder within a specific library. I will have to play around with it.

  4. Not so sure why my comment was deleted, but I was wondering if there is an option to delete the versions and leave the last 5 versions of the files?

    Thanks,
    Martin

      1. HI Patrick,

        This is amazing! It worked! Thanks a lot.
        Now do you have a script to delete previous version(and leave 5) for a specific folder in a library? That would help a lot

        Thanks,
        Martin

  5. This is an excellent script thank you so much for sharing! Now I’m trying to figure out how to set a cut-off date for the versions I’m keeping in a particular library… There has to be a way to do it. 🙂

    Thanks again – Extremely helpful!

    Mike

    1. Do you believe that a cutoff date would be beneficial?
      Depending on your SharePoint settings if not changed you could have up to 500 revisions of 1 file, let’s say if that 1 file is 10mb, and 500 revisions were all in 1 week.

      I don’t consider revisions in SharePoint as backups; they are more like autosave points in time. If I really need to restore a file, I will grab it from my Microsoft 365 backup solution instead of SharePoint eating up expensive production storage.

      Just my opinion.

      Thank you,
      Patrick Domingues

    1. Are you saying you cannot see the following 2 commands within the black box?

      Uninstall-Module -Name Microsoft.SharePoint.PowerShell
      Uninstall-Module -Name Microsoft.OnlineSharePoint.PowerShell

  6. Hi Patrick,

    Thanks for this article.
     
    I need help, I have SharePoint site in that there are multiple subsites are created and i want to delete all subsite version history leaving only last 5 version.

    Is there any ps script available?

    Thanks in advance.

  7. Hi Patrick thanks for this article.

    I have multiple subsites, is there any possible way where i can put all subsite URL in CSV file and run the script.
    Because here i’m manually updating the subsite link in the script and executing for version history deletion.

  8. Hi Patrick,

    Your guide has been really helpful so far. The script has cleaned up most of the version history of my files, but I’ve run into some errors like this:

    > Get-PnPProperty: /Users/fuad/user3.ps1:19
    > Line |
    > 19 | … $Versions = Get-PnPProperty -ClientObject $File -Property Versions
    > | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    > | Operation is not valid due to the current state of the object.

    When I check the files that have this error, I notice that they all have different last modified dates between the Storage Metrics menu and the Version History menu. For example, one file has a last modified date of 2/25/2024 in the Storage Metrics menu, but 10/18/2023 in the Version History menu.

    I uploaded all the files using Cyberduck with the option to preserve the modification date enabled. I’ve since disabled this option.

    Is there a way to batch clean up the remaining files that have this error? There are hundreds of them, and they’re taking up over 200GB of space.

    Thanks again for the script!

Leave a Comment

Stay Informed

Receive instant notifications when new content is released.