How can I restore files from a previous copy programmatically in OneDrive?

Mountain Pond 1,346 Reputation points

Hello, I need to recover a lot of encrypted data in OneDrive. I have prepared a script that can do this.

#Set Runtime Parameters
#Connect to SharePoint Online Admin Center
Connect-SPOService -Url $AdminSiteURL
#Add Site Collection Admin to the OneDrive
Set-SPOUser -Site $OneDriveSiteUrl -LoginName $SiteCollAdmin -IsSiteCollectionAdmin $True
Write-Host "Site Collection Admin Added Successfully!"

#Set Variables
$SiteURL= ""
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get All Files from the document library - In batches of 500
$ListItems = Get-PnPListItem -List $ListName -PageSize 500 | Where {$_.FileSystemObjectType -eq "File"}

foreach ($Item in $ListItems){
    $file = Get-PnPFile -Url $Item.FieldValues.FileRef
    $fileVersionLabel = Get-PnPFileVersion -Url $Item.FieldValues.FileRef

    IF ($file.Name -like "*royal_w*" -or $file.TimeLastModified -ge (Get-Date "4/3/2023")){
        # Restore
        $PreviousVersion = ($fileVersionLabel)[$fileVersionLabel.Count - 2]
        Restore-PnPFileVersion -Url $PreviousVersion.Url -Identity $PreviousVersion.ID -Verbose
    } ELSEIF ($file.TimeCreated -ge (Get-Date "4/3/2023")) {
        Remove-PnPFile -SiteRelativeUrl $Item.FieldValues.FileRef -Force -Verbose

In a test environment, everything is fine. But when in the production environment the script tries to process the OneDrive of a user who has a lot of data. Scenario after 2-3 hours, you get a response that the session was interrupted. Can be restored using this path BUT I need to do it programmatically. Please help make this happen. Thank you.

A Microsoft file hosting and synchronization service.
867 questions
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,871 questions
OneDrive Management
OneDrive Management
OneDrive: A Microsoft file hosting and synchronization service.Management: The act or process of organizing, handling, directing or controlling something.
1,149 questions
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,162 questions
0 comments No comments
{count} votes

Accepted answer
  1. Haoyan Xue_MSFT 20,906 Reputation points Microsoft Vendor

    Hi @Denis Pasternak ,

    Try to use the following code to restore files from a previous copy:

    #Set parameter values
       Function Restore-PreviousVersion()  
              [Parameter(Mandatory=$true)] [string] $SiteURL,  
              [Parameter(Mandatory=$true)] [string] $ListName  
              $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  
              $List = $Ctx.Web.Lists.GetByTitle($ListName)  
                  #Define Query to get List Items in batch  
              $Query = New-Object Microsoft.SharePoint.Client.CamlQuery  
              $Query.ViewXml = @"  
              <View Scope='RecursiveAll'>  
                     <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>  
                 <RowLimit Paged="TRUE">2000</RowLimit>  
                 #Get List Items in Batch  
             $ListItems = $List.GetItems($Query)  
             $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition  
                      #Iterate through each item and restore the previous version  
             Foreach($Item in $ListItems)  
                 #Get the file version  
                 $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  
         While($Query.ListItemCollectionPosition -ne $null)  
          Catch {  
              write-host -f Red "Error Getting List Items:" $_.Exception.Message  

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful