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

Mountain Pond 1,441 Reputation points
2023-04-06T16:52:46.65+00:00

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

#Set Runtime Parameters
$AdminSiteURL="https://abc-admin.sharepoint.com"
$OneDriveSiteUrl="https://abc-my.sharepoint.com/personal/isaiahl_devazlab_onmicrosoft_com"
$SiteCollAdmin="administrator@abc.onmicrosoft.com"
 
#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= "https://abc-my.sharepoint.com/personal/isaiahl_devazlab_onmicrosoft_com"
$ListName="Documents"
  
#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 https://www.zdnet.com/article/how-to-restore-deleted-or-modified-files-with-the-help-of-onedrive/ BUT I need to do it programmatically. Please help make this happen. Thank you.

OneDrive
OneDrive
A Microsoft file hosting and synchronization service.
1,142 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,822 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,272 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,592 questions
0 comments No comments
{count} votes

Accepted answer
  1. Xyza Xue_MSFT 25,471 Reputation points Microsoft Vendor
    2023-04-07T02:42:11.5466667+00:00

    Hi @Denis Pasternak ,

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

    #Set parameter values
    $SiteURL="https://yourdomain.sharepoint.com/sites/xyzax-version1"
    $ListName="doc2"
    
       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  
                       
              $List = $Ctx.Web.Lists.GetByTitle($ListName)  
              $Ctx.Load($List)  
              $ctx.ExecuteQuery()  
          
                  #Define Query to get List Items in batch  
              $Query = New-Object Microsoft.SharePoint.Client.CamlQuery  
              $Query.ViewXml = @"  
              <View Scope='RecursiveAll'>  
                 <Query>  
                     <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>  
                 </Query>  
                 <RowLimit Paged="TRUE">2000</RowLimit>  
             </View>  
    "@  
                 #Get List Items in Batch  
         Do  
         {  
             $ListItems = $List.GetItems($Query)  
             $Ctx.Load($ListItems)  
             $Ctx.ExecuteQuery()  
             $ListItems.count  
             $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition  
                      #Iterate through each item and restore the previous version  
             Foreach($Item in $ListItems)  
             {   
                 #Get the file version  
                 if($Item["File_x0020_Type"]){  
                 $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  
                 }  
                 }  
             }  
         }  
         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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.