SharePoint Online: Restore Previous Version of a Document using PowerShell

Requirement: Restore previous version of a document in SharePoint Online.

How to Restore a previous version of a document or Item in SharePoint Online?
When you restore a previous version of a list item or document, that version becomes the current version. You may want to restore a previous version when changes were made by mistake and you need to revert to an earlier state. To restore a previous version of a document or list item:
  • Go to your SharePoint Online document library and click on the ellipsis icon next to the document title.
  • From the context menu pop-up, Click on the ellipsis again and then choose the "Version History" menu item.
  • In version history page, Hover your mouse over the "Modified" date of the version you want to restore and click the arrow icon to get its context menu.
  • Click "Restore" and confirm the prompt with Yes to restore the particular version of a document.
    powershell to restore previous version in sharepoint online

SharePoint Online: Restore a Previous Version of All Items in a Document Library using PowerShell
While it's straightforward and simple in SharePoint Online to restore the previous version. Lets restore the previous version of all documents in a document library with PowerShell.
#Import SharePoint Online module
Import-Module Microsoft.Online.SharePoint.Powershell

Function Restore-PreviousVersion()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ListName
    )
   Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
        
        #Get all items from the list/library
        $Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $Ctx.Load($List)
        $ListItems = $List.GetItems($Query)
        $Ctx.Load($ListItems)
        $Ctx.ExecuteQuery()

        #Iterate through each item and restore the previous version
        Foreach($Item in $ListItems)
        { 
            #Get the file versions
            $File = $Ctx.Web.GetFileByServerRelativeUrl($Item["FileRef"])
            $Ctx.Load($File)
            $Ctx.Load($File.Versions)
            $Ctx.ExecuteQuery()

            If($File.Versions.Count -gt 0)
            {
                #Get the previous version's label
                $VersionLabel=$File.Versions[($File.Versions.Count-1)].VersionLabel

                #Restore the previous version
                $File.Versions.RestoreByLabel($VersionLabel)
                $Ctx.ExecuteQuery()
                Write-Host -f Green "Previous version $VersionLabel Restored on :" $Item["FileRef"]
            }
            Else
            {
                Write-host "No Versions Available for "$Item["FileRef"] -f Yellow
            }
        }
     }
    Catch {
        write-host -f Red "Error Removing User from Group!" $_.Exception.Message
    }
} 

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Documents"

#Call the function to restore previous document version
Restore-PreviousVersion -SiteURL $SiteURL -ListName $ListName

PnP PowerShell to Restore Previous Versions of All Files in a Library
To restore previous document versions in SharePoint Online, use this PnP PowerShell script.
#Function to Restore Previous Versions of all Files in a Library
Function Restore-PreviousVersion
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][Microsoft.SharePoint.Client.List]$Library
    )

    Begin
    {
        $BatchSize = 2000
        $global:Counter = 0
    }
    Process
    {
        #Get All Files from the Library in batches
        $AllItems = Get-PnPListItem -List $Library -PageSize $BatchSize -Fields ID -ScriptBlock { Param($items) $global:counter += $items.Count; `
                Write-Progress -PercentComplete ($global:Counter / ($Library.ItemCount) * 100) -Activity "Getting List Items of '$($_.Title)'" `
                     -Status "Processing Items $global:Counter to $($Library.ItemCount)";}  | Where {$_.FileSystemObjectType -eq "File"}
        Write-Progress -Activity "Completed Retrieving Items from List $($Library.Title)" -Completed
        
        #Process All Files from the Library
        $global:Counter = 1
        ForEach($Item in $AllItems)
        {
            #Get File and Versions from the List Item
            Get-PnPProperty -ClientObject $Item -Property File | Out-Null
            Get-PnPProperty -ClientObject $Item.File -Property Versions | Out-Null

            If($Item.File.Versions.Count -gt 0)
            {
                #Get the previous Version's Label
                $VersionLabel = $Item.File.Versions[$Item.File.Versions.Count-1].VersionLabel

                Write-Host "$(Get-Date) - ($($Counter)/$($AllItems.Count)) - Restoring version $VersionLabel for $($Item.File.Name)"
                $item.File.Versions.RestoreByLabel($VersionLabel)
                Invoke-PnPQuery
            }
            else
            {
                Write-Host "$(Get-Date) - ($($Counter)/$($AllItems.Count)) - Skipping $($Item.File.Name) as there are no previous versions!"
            }
            $Counter++
        }
    }
    end
    {
    }
}

#Set Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Projects"
$ListName = "Documents"

#Connect to SharePoint Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin

#Get the Library
$Library = Get-PnPList -Identity $ListName

#Call the function to Restore Previous Versions of all files
$Library | Restore-PreviousVersion
Here is my another post for SharePoint On-Premises to restore the previous version of a file using PowerShell: How to Restore the Previous Version of a File using PowerShell

1 comment:

  1. Would be great this example with list items instead :)

    ReplyDelete

Please Login and comment to get your questions answered!

Powered by Blogger.