SharePoint Online: Delete Version History using PnP PowerShell

Requirement: Delete version history in SharePoint Online.

How to Delete versions in SharePoint Online?
To delete previous versions of a file in SharePoint Online, follow these steps:
  • Navigate to your SharePoint Online document library, Select the file and then click on "Version History" from the toolbar. (or Select "Version History" from the context menu of the document)
  • On the version history page, You can choose "Delete" from the context menu of the particular version. To delete all versions of a document or list item, in the Version history page, click the "Delete All Versions" link, and then confirm the prompt.
    sharepoint online delete versions powershell
SharePoint Online: Delete Version History using PnP PowerShell
Lets delete all versions of all items in a list or library using PowerShell.
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$ListName="Documents"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get the Context
$Ctx= Get-PnPContext

#Get All Items from the List - Exclude 'Folder' List Items
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | 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 -f Yellow "Scanning File:"$File.Name
    
    If($Versions.Count -gt 0)
    {
        #Delete all versions
        $Versions.DeleteAll()
        $Ctx.ExecuteQuery()
        Write-Host -f Green "Deleted All Previous Versions of the File:"$File.Name
    }
}

PowerShell to Clear Previous Versions by Folder by Folder
Here is a different approach to clear previous versions of all files.
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName ="Documents"

#Function to Clear all File versions in a Folder
Function Cleanup-Versions([Microsoft.SharePoint.Client.Folder]$Folder)
{
    Write-host "Processing Folder:"$Folder.ServerRelativeUrl -f Yellow
    #Get the Site Relative URL of the folder
    $FolderSiteRelativeURL = $Folder.ServerRelativeURL.Replace($Web.ServerRelativeURL,"")

    #Get All Files from the folder    
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File
    
    #Iterate through each file
    ForEach ($File in $Files)
    {
        #Get File Versions
        $Versions = Get-PnPProperty -ClientObject $File -Property Versions 
        Write-host -f Yellow "`tScanning File:"$File.Name
     
        If($Versions.Count -gt 0)
        {
            #Delete all versions
            $Versions.DeleteAll()
            Invoke-PnPQuery
            Write-Host -f Green "`t`tDeleted All Previous Versions of the File:"$File.Name
        }
    }

    #Get Sub-folders from the folder - Exclude "Forms" and Hidden folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder | Where {($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))}
    Foreach($SubFolder in $SubFolders)
    {
        #Call the function recursively
        Cleanup-Versions -Folder $SubFolder     
    }
}
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$Web = Get-PnPWeb

#Get the Root Folder of the Library
$RootFolder = Get-PnPList -Identity $LibraryName -Includes RootFolder | Select -ExpandProperty RootFolder

#Call the function with Root Folder of the Library
Cleanup-Versions -Folder $RootFolder
You can cleanup previous versions of all files from a folder by replacing Line#45 with "$RootFolder = Get-PnPFolder -Url $FolderServerRelativeURL"

Keep Last Five Versions and Delete the Rest:
Going through the version history page and deleting one by one is cumbersome. Here is the PnP PowerShell to keep last 'N' versions and delete all others.
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$ListName="Documents"
$VersionsToKeep = 5

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get the Context
$Ctx= Get-PnPContext

#Get All Items from the List - Exclude 'Folder' List Items
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | 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 -f Yellow "Scanning File:"$File.Name
    $VersionsCount = $Versions.Count
    $VersionsToDelete = $VersionsCount - $VersionsToKeep
    If($VersionsToDelete -gt 0)
    {
        write-host -f Cyan "`t Total Number of Versions of the File:" $VersionsCount
        #Delete versions
        For($i=0; $i -lt $VersionsToDelete; $i++)
        {
            write-host -f Cyan "`t Deleting Version:" $Versions[0].VersionLabel
            $Versions[0].DeleteObject()
        }
        $Ctx.ExecuteQuery()
        Write-Host -f Green "`t Version History is cleaned for the File:"$File.Name
    }
}
You can apply this cleanup to all files with in a specific folder or sub-folder by:
$ListItems = Get-PnPListItem -List $ListName -FolderServerRelativeUrl $FolderServerRelativeURL -PageSize 2000

This script leaves the recent 'N' number of versions and deletes all previous versions of the documents. To clean up older versions in SharePoint Online using PowerShell CSOM, refer: SharePoint Online: Delete Version History using PowerShell CSOM

Don't forget to set a limit for the number of versions under:  List/Library Settings >> Versioning settings to prevent any further versions growing beyond your limit.

11 comments:

  1. I am getting the following errors, any idea?
    Exception calling "ExecuteQuery" with "0" argument(s): "Cannot invoke method or retrieve property from null object.
    Object returned by the following call stack is null. "File
    ""
    At line:10 char:5
    + $Ctx.ExecuteQuery()
    + ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServerException

    ReplyDelete
  2. Hi there

    I ran the script but I get this message now

    Get-PnPListItem : The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.

    Regards

    Eric

    ReplyDelete
  3. Hi this works a treat now you have done a great job on this thank you so much

    ReplyDelete
  4. Thank you for these!

    When using "Keep Last Five Versions and Delete the Rest" is there a way to specify the exact sub folder in a library? For example: .sharepoint.com/sites/marketing/documents/proposals/2019

    ReplyDelete
    Replies
    1. Use this line to get all files from a given folder:
      $ListItems = Get-PnPListItem -List $ListName -FolderServerRelativeUrl $FolderServerRelativeURL -PageSize 2000 | Where {$_.FileSystemObjectType -eq "File"}

      Delete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I love most all your articles; however, this is one that did not work for me...at all. I had to enumerate through each version and $Version.DeleteObject()

    Received errors every time I used $Version.DeleteAll() [Method invocation failed because [Microsoft.SharePoint.Client.ListItemVersion] does not contain a method named 'DeleteAll']

    ReplyDelete
    Replies
    1. Well, Versioning features were added to PowerShell CSOM's later build. I would suggest to update the PnP PowerShell module once and give it a try!
      Update-Module SharePointPnPPowerShellOnline

      Delete
    2. That's what I thought, too. I updated the module, but still nothing.

      I think this one's a no-go for me, my friend. I still very much love the site - use it weekly!

      Thank you.

      Delete
    3. The Version Collection object has DeleteAll(), But individual version has only DeleteObject() method!

      Delete

Please Login and comment to get your questions answered!

Powered by Blogger.