Tuesday, May 6, 2025

PowerShell script to delete file versions from the specified SharePoint document library

Managing file versions in SharePoint Online is essential to maintain storage hygiene and performance, especially when versioning is enabled for document libraries. Over time, older versions of files can accumulate and consume significant storage space. This PowerShell script demonstrates how to connect to a SharePoint Online site and delete all previous versions of files from a specified document library.

  Prerequisites

  • PnP PowerShell Module installed (Install-Module -Name "PnP.PowerShell")
  • Permissions to access the SharePoint Online site and document library
  • SharePoint versioning must be enabled for the document library

📝 Script Overview

$SiteURL = "https://{domain}.sharepoint.com/sites/GKS_Demosite"
$ListName="TestVersionsDocLib"
Connect-PnPOnline -Url $SiteURL -UseWebLogin
#Get the Context
$Ctx= Get-PnPContext
#Get All Items from the List - Exclude 'Folder' List Items
$ListItems = Get-PnPListItem -List $ListName | Where {$_.FileSystemObjectType -eq "File"}
ForEach ($Item in $ListItems)
{
    #Get File Versions
    $File = $Item.File
    $Versions= $File.Versions
    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()
    Write-host  "Scanning File:"$File.Name
     
    If($Versions.Count -gt0)
    {
        #Delete all versions
        $Versions.DeleteAll()
        $Ctx.ExecuteQuery()
        Write-Host  "Deleted All Previous Versions of the File:"$File.Name
    }
}

📝 What the Script Does

  1. Connects to the specified SharePoint Online site using PnP PowerShell.
  2. Retrieves all file items from the specified document library (excluding folders).
  3. Loads each file’s version history.
  4. Deletes all previous versions for each file, keeping only the latest one.

⚠️ Important Notes

  • This script permanently deletes all previous versions. Make sure this is what you intend before running it.
  • Test the script in a non-production environment first.
  • You may want to add logging or backups depending on your organization’s governance policies.

🧠 Use Cases

  • Reclaiming storage space in libraries with heavy versioning.
  • Maintaining SharePoint Online quota limits.
  • Cleaning up outdated versions during migration or audits.

No comments:

🏢 Monitoring and Optimizing Microsoft 365 SharePoint Sites for Efficiency and Governance

  📌 Introduction As organizations increasingly rely on Microsoft 365 for collaboration and content management, SharePoint Online has become...