SharePoint Online: Restore a Document from the Recycle Bin using PowerShell

Requirement: Recover a deleted document from the recycle bin in SharePoint Online.

How to Restore from Recycle Bin in SharePoint Online?

When you delete a document from the SharePoint Online document library, it just moves to the SharePoint Recycle Bin, similar to what happens when you delete a document on your local computer to prevent data loss. There are two stages of Recycle bins in SharePoint Online. When an item is deleted, it goes to the first-stage Recycle Bin (or end-user Recycle Bin). When you delete an item from the first-stage Recycle Bin, it is moved to the second-stage Recycle bin, which Site Collection Administrators can access. The total lifetime of deleted items is 93 days. When it reaches the retention period of 93 days, the item gets deleted permanently from the Recycle Bin (it doesn’t matter if it’s in the first or second stages). How to recover a deleted file in SharePoint Online?

To restore items from the recycle bin, follow these steps:

  1. Login to your SharePoint site and click on “Site Contents”, either from the site settings icon in the top-right corner or from the quick launch menu.
  2. Click on the “Recycle bin” link from the top-right area of the page. This is called the “End-user Recycle Bin”, which lists all items deleted either by you or by someone else. (As long as you have edit permission to the deleted items, you can view and restore them from here!).
  3. This page lists all deleted files on the SharePoint Online site, sorted by deleted date. Select the document(s) you would like to restore and then click “Restore Selection”.
    sharepoint online restore from recycle bin powershell
  4. Confirm restore by clicking the “OK” button.
  5. The files you selected should be available in the original location from where it was deleted.

Restore Deleted Documents from Admin Recycle bin:

As the end-user recycle bin is security trimmed, You can use the Site collection Admin recycle bin to view and restore documents deleted by end-users at the site collection level. Login to the site as a site administrator, Go to Site Settings and click on the “Recycle Bin” link under the “Site Collection Administration” section (URL shortcut: “/_layouts/15/AdminRecycleBin.aspx”) to restore deleted files.

Recover Documents from Second Stage Recycle Bin:

Documents deleted from the first stage Recycle Bin (or end-user recycle bin) don’t get deleted permanently as long as its retention time is lesser than 93 days. Instead, they are moved to the second stage, which can be accessed by the site collection administrator. It’s a good idea to empty the recycle bin if your storage quota reaches its maximum, as deleted SharePoint data occupy the site’s storage space.

Follow these steps to recover from the second-stage Recycle Bin:

  1. Log in to the SharePoint Online Site as the site collection administrator.
  2. Click the Settings gear icon >> Site information >> and choose “View all site settings”.
  3. On the Site Settings page, click the Recycle Bin link under the Site Collection Administration section.
  4. Click on the “Second-stage recycle bin” link from the bottom of the page. (URL short-cut for second Stage Recycle bin:/_layouts/15/AdminRecycleBin.aspx?view=5#view=13)
  5. Select the SharePoint files you wish to restore and click “Restore.

That’s all. The deleted SharePoint file will be restored to its original place. Now, let’s see the SharePoint Online PowerShell to restore items from the recycle bin.

SharePoint Online: Restore from Recycle bin using PowerShell

In SharePoint Online, we can restore deleted files using PowerShell. E.g., let’s use PowerShell to restore all Excel files from recycle bin to their original location.

#Load SharePoint Online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
   
##Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/Sales/"
$UserName="Salaudeen@crescent.com"

#Get the password to connect 
$Password = Read-host -assecurestring "Enter Password for $UserName"
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$Password)
 
Try {    
    #Setup the context
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $Context.Credentials = $Credentials
    
    #Get the Site recycle bin
    $Site = $Context.Site
    $RecycleBinItems = $Site.RecycleBin
    $Context.Load($Site)
    $Context.Load($RecycleBinItems)
    $Context.ExecuteQuery()

    #Get all Excel files from Recycle bin
    $ExcelFiles= $RecycleBinItems | Where {$_.Title -like "*.xlsx"}
    Write-Host "Total Number of Excel Files found Recycle Bin:" $ExcelFiles.Count
    
    #Restore from Recylce bin
    $ExcelFiles | ForEach-Object { $_.Restore() }
    $Context.ExecuteQuery()    
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Please note that the above script restores from 1st stage recycle bin (or end-user recycle bin). Instead of a Web object, you may have to use a Site object to restore from the Site collection Recycle bin (Or 2nd stage recycle bin).

SharePoint Online: Restore a File from Recycle bin using PnP PowerShell

We can also restore deleted files in SharePoint Online using PnP PowerShell. To restore items from the recycle bin, as a first step, let’s get the ID of an item to restore:

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"

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

#Get All Items from Recycle bin
Get-PnPRecycleBinItem -RowLimit 500000 | Select Title, ID, ItemType, Size, ItemState, DirName, DeletedByName, DeletedDateLocalFormatted | Format-table -AutoSize 

This gets you all items in the recycle bin with their IDs.

Use -RowLimit switch to add pagination to recycle bin items and avoid threshold exceed issue: “Get-PnPRecycleBinItem: The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator”.
E.g.  Get-PnPRecycleBinItem -SecondStage -RowLimit 5000
powershell to get recycle bin items in sharepoint online

Now, you can restore the item with the ID parameter using the Restore-PnPRecycleBinItem cmdlet.

#Restore Recycle Bin Item by ID
Restore-PnPRecycleBinItem -Identity fd97143c-68fc-48ef-b148-5b6228610899 -Force

SharePoint Online: Restore bulk from recycle bin using PowerShell

If you want to restore all items from the recycle bin, use the following:

#Restore All Items from recycle bin
Get-PnPRecycleBinItem -RowLimit 500000 | Restore-PnpRecycleBinItem

Similarly, you can restore a file by its name or type. E.g., Let’s restore all documents (.docx)

Get-PnPRecycleBinItem -RowLimit 500000 | Where {$_.LeafName -like "*.docx"} | Restore-PnpRecycleBinItem -Force

Restore All Files and Folders Deleted from a Specific Library using PowerShell

What if a new file or folder with the same name was created meanwhile? Maybe the folder was recreated, and the file was re-uploaded to the original location where it was deleted. Let’s perform a check before restoring it from the recycle bin.

#Parameter
$SiteURL= "https://crescent.sharepoint.com/sites/marketing"
$DirPath = "sites/marketing/Migration"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Get the Web
$Web = Get-PnPWeb
 
#Get All Items deleted from a specific path or library - sort by most recently deleted
$DeletedItems = Get-PnPRecycleBinItem -RowLimit 500000 | Where { $_.DirName -like "$DirPath*"} | Sort-Object -Property DeletedDate -Descending

#Restore all deleted items from the given path to its original location
ForEach($Item in $DeletedItems)
{
    #Get the Original location of the deleted file
    $OriginalLocation = "/"+$Item.DirName+"/"+$Item.LeafName
    If($Item.ItemType -eq "File")
    {
        $OriginalItem = Get-PnPFile -Url $OriginalLocation -AsListItem -ErrorAction SilentlyContinue
    }
    Else #Folder
    {
        $OriginalItem = Get-PnPFolder -Url $OriginalLocation -ErrorAction SilentlyContinue
    }
    #Check if the item exists in the original location
    If($OriginalItem -eq $null)
    { 
        #Restore the item
        $Item | Restore-PnpRecycleBinItem -Force
        Write-Host "Item '$($Item.LeafName)' restored Successfully!" -f Green
    }
    Else
    {
        Write-Host "There is another file with the same name.. Skipping $($Item.LeafName)" -f Yellow
    }
}

To restore a deleted site in SharePoint Online, You have to use either PowerShell or SharePoint Admin Center. Here is my other post on restoring deleted items from recycle bin: SharePoint Online: PowerShell to Restore Deleted Items from Recycle bin

How to recover a deleted document library in SharePoint Online?

To recover a deleted document library in SharePoint Online, you can go to the SharePoint site where the library was located. In the Quick Launch bar navigation on the bottom left of the screen, click on “Recycle Bin”. From there, you can select the deleted library and restore it to its original location by selecting it and then clicking the “Restore” button. It’s important to note that deleted items are only kept in the recycle bin for 93 days, so it’s best to act quickly if you need to recover a deleted library.

How do I recover permanently deleted files from SharePoint Online?

To recover permanently deleted files from SharePoint Online, you can use the Retention Policies or use a third-party data recovery tool. If both options are unavailable, You have to contact Microsoft support for assistance. It’s important to note that there is a limited time frame for recovering deleted files, so it’s best to act quickly.

Can you search the Recycle Bin in SharePoint?

Yes, you can search the Recycle Bin in SharePoint Online. Simply go to the Recycle Bin and use the search bar to find the item you are looking for. You can also filter by date deleted, item type, and other criteria to narrow down your search results. You can also use PowerShell to search and export deleted items in Recycle bin

Who can see the recycle bin in SharePoint?

Any Site Member (with Edit permissions level) or Site/Group Owner (with Full Control permission level) can see the recycle bin in SharePoint Online. For Team Sites (with or without Office 365 Groups), the Recycle Bin link is permanently and prominently located on the Quick Launch (left-hand-side menu). If the Recycle Bin is not visible in the Quick Launch bar, administrators can locate it by clicking on Settings and then on Site Contents.

How do I find the Recycle Bin in SharePoint Online?

To access the Recycle Bin in SharePoint Online, follow these steps: Go to the SharePoint Online site, click the settings gear icon in the top-right corner, and select “Site contents”. Click on the “Recycle Bin” link on the site contents page. If you have site collection Admin permissions, you can access the site collection Recycle Bin under the Site settings page!

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!

8 thoughts on “SharePoint Online: Restore a Document from the Recycle Bin using PowerShell

  • This headache happened to us – 200,000 files deleted and it would take forever to restore them via this command, so we did a restore document library.

    Now its restored but we’re supposed to get the list of deleted files that user deleted as proof but we failed to do so before restoring them.

    Now its nowhere to be found in Recyclebin after restore.
    Another way, however is going to Restore this Library > then select custom date and it will load all of the activities from Date 0 (today) upto the date you wish to see (for us, 9 days in total)
    But scrolling down (approximately 300,000+ history) would take us forever to get the 9 days result.

    Do we have a PnP powershell function that could have same function as to view history on restore library on a specific date range?

    Thank you

    Reply
  • This works but Restore-PnpRecycleBinItem is PAINFULLY slow. I had someone accidentally delete around 34,000 files just earlier and it’s probably going to take more than 24 hours to restore everything. Using the GUI is actually faster!!

    Reply
  • How can you restore files deleted by a particular user within a specific time?

    Reply
    • That is exactly the same question I’d like to ask. I do not get the script to work properly at all.

      Reply
      • You can have this using where condition on column DeletedByName :

        Here is the sample :

        $noofDaystogetfrom=-20;
        $restoreDate = (Get-Date).AddDays($noofDaystogetfrom)
        $RecycleBinItems=Get-PnPRecycleBinItem | where {($_.DeletedByName -eq “System Account”) -and ($_.DeletedDate -gt $restoreDate)}
        $RecycleBinItems | Restore-PnPRecycleBinItem -Force

        Reply
  • A colleague managed to delete a whole departments files (60,000 in 7700 folders) from SharePoint Online – manually restoring them with the GUI has proved to nearly impossible (many timeout errors) so I stumbled upon your page in searching for a PowerShell solution. I’m a novice at PowerShell but it must surely be possible to restore all items in the recycle bin or even better all items in the recycle bin deleted by a specific user? Are you able to help with this?

    Reply
    • Sure, Just removed the “Where” class in Line#26 and run the script in PowerShell ISE!

      Reply

Leave a Reply

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