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:

๐Ÿง  Steps to Build a POC Locally with Windows AI Foundry

  ๐Ÿš€ Introduction What is Foundry Local? Foundry Local brings the power and trust of Azure AI Foundry to your device. It includes everything...