SharePoint Online: Restore Deleted Items from Recycle Bin using PowerShell

Requirement: Restore Items from recycle bin in SharePoint Online using PowerShell

How to Restore Items 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 recycle bin in SharePoint Online site is more or less similar to what you have on your local PC, and it lets you view and restore the items that have been deleted from your site.

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

  • Navigate to the SharePoint Online site where you want to restore deleted items from the recycle bin. 
  • Click on Settings gear >> Choose the “Site Contents” link from the site settings menu.
  • On the Site Contents page, click the Recycle Bin link, located to the top-right section. 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
  • To restore items from the site recycle bin, On the Recycle Bin page, check the box for each item you want to restore and click the “Restore Selection” link.
    sharepoint online restore from recycle bin powershell

The selected items are restored, and the 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.

Restore Deleted Items from Site Collection Recycle bin

If you have Site collection administrator rights, you can use “Site collection Recycle bin” and restore items for any site in the site collection. Here is how to restore a folder in SharePoint Online:

  • Navigate to the top-level site in the site collection (Root Web).
  • Click on Settings >> Select “Site Settings” link from the Settings menu.
  • On the Site Settings page, click on the “Recycle Bin” link from the “Site Collection Administration” section. Now, you can follow the same steps to restore any item in the Site collection Administrator recycle bin.
    sharepoint online recycle bin restore powershell

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 check who has deleted a file in SharePoint Online? Just look at the “Deleted by” Column!

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 files. 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 7 days using PnP PowerShell.

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

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

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

#Get All Items deleted from a specific path or library
$DeletedItems = Get-PnPRecycleBinItem | 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 | 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
    }
}
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 | Restore-PnpRecycleBinItem

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

Get-PnPRecycleBinItem | Where { $_.DeletedByEmail -eq "[email protected]"} | Restore-PnpRecycleBinItem -Force

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

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

10 thoughts on “SharePoint Online: Restore Deleted Items from Recycle Bin using PowerShell

  • 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