SharePoint Online: Restore the Previous Version of a Document using PowerShell

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

How to Restore a previous version of a document or Item in SharePoint Online?

You may want to restore a previous version when changes were made mistakenly, and you need to revert to an earlier state. To restore an earlier version of a document or list item, follow these steps:

  1. Navigate to your SharePoint Online document library, where the files you want to restore the previous version are located.
  2. View the version history by right-clicking on the file >> From the context menu pop-up, choose the “Version History” menu item.
  3. Select the Version to Restore: On the 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.
  4. Click “Restore” and confirm the prompt with Yes to restore the particular version of a document.
    powershell to restore previous version in sharepoint online

It’s a good idea to View/Download the specific version to ensure you are restoring the correct version. The restore version operation creates a new version – meaning you will never lose any versions while performing this process.

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, let’s 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()
        [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)
        $ListItems = $List.GetItems($Query)

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

            If($File.Versions.Count -gt 0)
                #Get the previous version's label

                #Restore the previous version
                Write-Host -f Green "Previous version $VersionLabel Restored on :" $Item["FileRef"]
                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

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

When you restore a previous version of a list item or document, that version becomes the current version.

PnP PowerShell to Restore Previous Versions of a File

To restore the previous version of a file, use the Restore-PnPFileVersion cmdlet:

$SiteURL = ""
$FileURL = "/sites/Retail/Shared Documents/Invoice-ID-022.xlsx" #Server Relative URL

#Connect to SharePoint Online Site
Connect-PnPOnline -Url $SiteURL -Interactive
#Remove previous version with version Label or ID 
Restore-PnPFileVersion -Url $FileURL -Identity "1.0" -Force

This can be useful if you accidentally overwrite a file, or if you need to revert to an older version of a document. Use this PnP PowerShell script to restore previous document versions of all files in a SharePoint Online document library:

#Function to Restore Previous Versions of all Files in a Library
Function Restore-PreviousVersion

        $BatchSize = 2000
        $global:Counter = 0
        #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)"
                Write-Host "$(Get-Date) - ($($Counter)/$($AllItems.Count)) - Skipping $($Item.File.Name) as there are no previous versions!"

#Set Parameters
$SiteURL = ""
$ListName = "Documents"

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

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

#Call the function to Restore Previous Versions of all files
$Library | Restore-PreviousVersion

Restoring previous versions can help you recover lost or deleted content and revert to older versions of documents. Here is my other 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?

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

4 thoughts on “SharePoint Online: Restore the Previous Version of a Document using PowerShell

  • Hello Salaudeen Rajack.
    This script works perfect but it restores all files on a OneDrive account. Are you able to show how to create a new list with items so we can restore a specific folder in OneDrive?
    Like “OneDrive – Company Name\Documents\Test\” – in this folder are files and folders and only they need to be restored.
    Many thanks and best regards

    • Instead of getting all files from the library, you can use this script to get files from a folder:

      $FolderServerRelativePath = "/sites/Marketing/Branding/2020*" #Any file under the given folder path
      $FolderItems = Get-PnPListItem -List $ListName -PageSize 2000 | Where {$_.FieldValues.FileRef -like $FolderServerRelativePath -and $_.FileSystemObjectType -eq "File" } 
  • great script! I was wondering if you could also make it work if the document library contains folders and revert the files inside those folders + subfolders. And if possible to target files modified by a specific user. Thanks!

  • Would be great this example with list items instead 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *