SharePoint Online: Restore Deleted Files from Recycle Bin using PowerShell

Requirement: Restore Files from recycle bin in SharePoint Online using PowerShell.

How to Restore Files from Recycle bin in SharePoint Online?

There are times when we might find ourselves needing a way of retrieving deleted files or folders that have been mistakenly deleted. The SharePoint recycle bin is more or less similar to what you have on your Windows recycle bin on your desktop, letting you view and restore the items that have been missing/corrupted/deleted from your site. As there are no built-in backups available for SharePoint Online, recycle bin can help you to recover deleted items and prevent data loss for up to 93 days. So, How do I recover a deleted file in SharePoint Online?

To restore Items from SharePoint Online recycle bin, do the following:

  1. Navigate to the SharePoint site where you want to restore deleted items from the recycle bin. 
  2. Click on the Settings gear icon >> Choose the “Site Contents” link from the site settings menu.
  3. On the Site Contents page, click the Recycle Bin link in the upper-right corner. You will be navigated to the Recycle Bin page for the site (not site collection!), which lists all items in the recycle bin. sharepoint online recycle bin restore powershell
  4. To restore items from the site recycle bin, check the box for each item you want to restore on the Recycle Bin page and click the “Restore” button. Select all items if you wish to all your files back. Alternatively, you can select only the files you wish to restore and click Restore.
    sharepoint online restore from recycle bin powershell

The selected items are restored, and the end-user Recycle Bin page is refreshed to reflect the change. This can be useful if you accidentally delete an item or if it is deleted by someone else, and you need to restore it. If you don’t find the deleted files in the first-stage recycle bin, you can search in the second-stage recycle bin.

Recover Deleted Files and Folders from Site Collection Recycle bin

If you have Site collection administrator permissions, you can use the “Site collection Recycle bin” and restore items for any site in the site collection. If an item is deleted from the site collection Recycle Bin, or it exceeds the retention time, it is permanently deleted. Here is how to restore a folder in SharePoint Online:

  1. Navigate to the top-level site in the site collection (Root Web) as a site administrator.
  2. Click on the Settings icon >> Select the “Site Settings” link from the Settings menu.
  3. On the Site Settings page, click on the “Recycle Bin” link from the “Site Collection Administration” section.
  4. Find and select the deleted document and click on “Restore selection”.
    sharepoint online recycle bin restore powershell

Now, you can follow the same steps to restore any item in the Site collection Administrator recycle bin.

Make sure you don’t have a file or folder with the same name in the recycle bin. Otherwise, you’ll end up with an error: “A folder with this name “Folder Name” already exists in “Location”. To restore the folder, rename the existing folder and try again.”. Similarly, we can restore deleted items such as files or folders using PowerShell.

How to recover deleted document library in SharePoint Online?

If you have ever accidentally deleted a document library in SharePoint Online, follow the steps below to recover it.

  1. Go to the SharePoint Online site where you deleted the document library.
  2. Click on settings in the upper right-hand corner and select Site Information >> View All Site Settings.
  3. On the site settings page, scroll down to the site collection administration section and click on “Recycle bin”.
  4. Find the document library that you accidentally deleted and click on the restore button next to it. If you don’t find it there, check the “Second-stage” recycle bin.
  5. That’s it! Your document library has now been successfully restored.
How to check who has deleted a file in SharePoint Online? Just look at the “Deleted by” Column!

Lists, list items, libraries, files, and versions of files can be restored to their original place if their parents have not already been deleted. If a file has been deleted, you can’t restore a version of a file. It’s because deleting a file deletes all versions of the file. The same applies if the library to which the file belonged has been deleted. A library must be restored before the file can be restored. 

How do I recover permanently deleted files from SharePoint Online? Administrators can contact Microsoft Support if the content is not found in end-user and site collection Recycle Bins.

SharePoint Online: PowerShell to Restore Items from Recycle Bin

Let’s restore all items deleted by a particular user in a SharePoint Online site collection:

#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/marketing"
$DeletedByUserEmail = "[email protected]"

#Get Credentials to connect
$Cred= Get-Credential
  
Try {    
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
     
    #Get the Site recycle bin
    $Site = $Ctx.Site
    $RecycleBinItems = $Site.RecycleBin
    $Ctx.Load($Site)
    $Ctx.Load($RecycleBinItems)
    $Ctx.ExecuteQuery()
 
    #Get all items deleted by a specific user
    $DeletedItemsByUser = $RecycleBinItems | Where {$_.DeletedByEmail -eq $DeletedByUserEmail}
    Write-Host "Total Number of Items Deleted by User in Recycle Bin:" $DeletedItemsByUser.Count
     
    #sharepoint online restore deleted files using PowerSehll
    $DeletedItemsByUser | ForEach-Object { $_.Restore(); Write-host "Restored Itme:"$_.Title }
    $Ctx.ExecuteQuery()    
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This PowerShell recovers deleted SharePoint files and folders. Similarly, we can restore items deleted based on the deleted date.

SharePoint Online PowerShell to Restore Items from Recycle Bin

Let’s restore all items deleted today! Here is how to restore bulk from recycle bin using PowerShell:

#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/marketing"
$DeletedDate = (Get-Date).Date #Get Today's Date

#Get Credentials to connect
$Cred= Get-Credential
  
Try {    
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
     
    #Get the Site recycle bin
    $Site = $Ctx.Site
    $RecycleBinItems = $Site.RecycleBin
    $Ctx.Load($Site)
    $Ctx.Load($RecycleBinItems)
    $Ctx.ExecuteQuery()
 
    #Get all items deleted on given date
    $DeletedItems = $RecycleBinItems | Where { ($_.DeletedDate).Date -eq $DeletedDate }
    Write-Host "Total Number of Items Deleted on given Date:" $DeletedItems.Count
     
    #Restore items from Recylce bin
    $DeletedItems | ForEach-Object { $_.Restore(); Write-host "Restored Item:"$_.Title }
    $Ctx.ExecuteQuery()    
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
} 
How about First Stage and Second Stage Recycle Bin?
By default, these scripts get deleted items from both stages! In CSOM: To Get Recycle bin items based its stage, use: ItemState -eq “FirstStageRecycleBin” or “SecondStageRecycleBin”. Similarly, in PnP PowerShell: use the parameters either -FirstStage or -SecondStage with cmdlet: Get-PnPRecycleBinItem to filter recycle bin items accordingly!

PnP PowerShell to Restore Recycle bin Items in SharePoint Online

Let’s restore items deleted in the past seven days using the PnP PowerShell script.

#Parameter
$SiteURL= "https://crescent.sharepoint.com/sites/marketing"

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

#Get All Items Deleted in the Past 7 Days
$DeletedItems = Get-PnPRecycleBinItem -RowLimit 500000 | Where { $_.DeletedDate -gt (Get-Date).AddDays(-7) }

#Restore Recycle bin items matching given query
$DeletedItems | Restore-PnpRecycleBinItem -Force

Restore All Files Deleted from a particular SharePoint Online Library

Similarly, you can restore all items deleted from a specific site, subsite, library, or folder using PowerShell:

#Parameter
$SiteURL= "https://crescent.sharepoint.com/sites/marketing"
$DirPath = "sites/marketing/Shared Documents"

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

#Get All Items deleted from a specific path or library
$DeletedItems = Get-PnPRecycleBinItem -RowLimit 500000 | Where { $_.DirName -like "$DirPath*"} | Restore-PnpRecycleBinItem -Force

How about skipping the file or folder if it exists already?

#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
    }
}

How can you restore files deleted by a particular user within a specific time using PowerShell? Sure, Here is how:

$SiteURL = "https://crescent.sharepoint.com/sites/Retail"
#Set From and To Date
$FromDate = Get-Date("01/15/2021")
$ToDate= Get-Date("02/15/2021")
$DeletedByEmail = "[email protected]"

#Connect to Site
Connect-PnPOnline -Url $SiteURL -Interactive

#Restore All Items deleted between given date and by a specific user
$DeletedItems = Get-PnPRecycleBinItem -RowLimit 500000 | Where {($_.DeletedDate -ge $FromDate -and $_.DeletedDate -le $ToDate) -and ($_.DeletedByEmail -eq $DeletedByEmail)} | Sort-Object -Property DeletedDate -Descending

SharePoint Online: Restore all files deleted by a particular user

To restore all files deleted by a particular user, use the:

Get-PnPRecycleBinItem -RowLimit 500000 | Where { $_.DeletedByEmail -eq "[email protected]"} | Restore-PnpRecycleBinItem -Force
SharePoint Online: Bulk Restore All Items in Recycle Bin
To restore all Items from the recycle bin, simply remove the “where” clause from the script!
Get-PnPRecycleBinItem -RowLimit 500000 | Restore-PnpRecycleBinItem

Here is another post on restoring files from recycle bin: SharePoint Online: Restore Files from Recycle bin using PowerShell

How do I empty the Recycle Bin in SharePoint Online?

Navigate to your SharePoint Online site, and click on “Recycle bin” from quick launch navigation. You can also access the Recycle bin from Site Settings >> Choose “Site Contents”>> Click on the “Recycle Bin” link in the top-right corner. On the recycle bin page, click on the “Empty recycle bin” button in the toolbar!
More info: Empty recycle bin in SharePoint Online using PowerShell

How do I delete a site collection from recycle bin SharePoint Online?

Deleted site collections go into the tenant-level recycle bin. You can remove the deleted site permanently, either from the SharePoint Admin center: In SharePoint Online Admin Center, click on “Sites”>> “Deleted Sites”>> Select the site from the list and click on the “Delete” button in the toolbar. You can also use PowerShell to empty recycle bin.
More info: Permanently delete a site collection in SharePoint Online

How do I access SharePoint Online recycle bin?

To access the Recycle Bin in SharePoint Online, Navigate to the SharePoint site >> Click on the Settings gear icon >> Choose “Site Contents”. On the Site Contents page, click the Recycle Bin link in the top-right corner.

How do I recover a deleted subsite in SharePoint online?

Deleted subsites go to the second-stage site collection recycle bin! Go to the SharePoint Online site collection where you deleted the subsite. Click on the settings gear, Select Site Information >> View All Site Settings. On the site settings page, scroll down to the site collection administration section and click on “Recycle bin”. Click on the “Second-stage recycle bin” link on the bottom >> Select the subsite and click on the “Restore” button in the command bar to start restoring the subsite.
More info: SharePoint Online recover deleted subsite

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!

16 thoughts on “SharePoint Online: Restore Deleted Files from Recycle Bin using PowerShell

  • Hello,

    i need a script to restore all files Deleted in the Past 7 Days from all the sites.

    Can you help with that please ?

    Thank you

    Reply
  • Hello,
    when i run the script for restore by particualr Email id, i get the below error

    Error: Exception calling “ExecuteQuery” with “0” argument(s): “Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))”

    Reply
  • Salaudeen, this is a VERY useful script, thank you! How can I apply the RowLimit to the script that restores all items deleted by a particular user? Thanks in advance for your response!!

    Reply
    • Quick dirty workaround: Use Get-PnPRecycleBinItem -Rowlimit 5000 | Where { $_.DeletedByEmail -eq “[email protected]”} | Restore-PnpRecycleBinItem -Force

      And run the above multiple times until you restore all items deleted by the user.

      Reply
  • How do you extend the request message larger than 2MBs? Set-TransportConfig or MaxReceivedMessageSize don’t work for SharePoint 16, only 15. Or maybe I’m doing something wrong?

    Reply
  • Hi, the previous IT implemented a retention policy to delete files after 1 year. Now I need to recover all the deleted files deleted by the user System account.

    When I tried to recover everything I got this error: Get-PnPRecycleBinItem : The attempted operation is prohibited because it exceeds the list view threshold.

    How can I fix this please?

    Reply
    • Add “RowLimit” parameter to the Get-PnPRecycleBinItem cmdlet! E.g., Get-PnPRecycleBinItem -RowLimit 5000

      Reply
  • May I restore deleted files from 2nd-stage Recycle Bin even after they are deleted again from 2nd-stage Recycle Bin?

    Reply
    • Any item deleted from the 2nd stage recycle bin can be restored – Only by Microsoft support! (Unless you have a retention policy in place already!)

      Reply
  • Hi , While restoring items in bulk, getting an error “a file with this name already exists”

    $tobeRestoredCollection | Restore-PnPRecycleBinItem -Force
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Restore-PnPRecycleBinItem], ServerException
    + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.RecycleBin.RestoreRecycleBinItem
    Restore-PnPRecycleBinItem : A file with this name “PCMTest.pdf” already exists in “personal/testuser_domain_com/docs/sales”
    file, rename the existing file and try again.

    Can you guide me on how to resolve this.?

    Reply
  • I get O deleted document when replacing Today with another date

    Reply
  • How do I check if the item restored already exists in its original location? E.g. I’ve had a file in a folder, delete it and then re-uploaded. Deleted and re-uploaded again. Now, I want to restore the most recent file making sure it doesn’t exists in the target. Please help.

    Reply

Leave a Reply

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