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, the 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. Click the Recycle Bin link in the upper-right corner on the Site Contents page. 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

PowerShell is an effective way to restore deleted files in SharePoint Online that are still in the 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 = "salaudeen@crescent.com"

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

These steps can be used to restore deleted files from the Recycle Bin easily and efficiently.

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 = "salaudeen@crescent.com"

#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 "salaudeen@crescent.com"} | 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

Let’s restore all files deleted by a particular user, with progress bar:

$SiteURL = "https://crescent.sharepoint.com/sites/london"

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

#Get Deleted Items
$DeletedItemsBySystemAccount = Get-PnPRecycleBinItem -RowLimit 5000000 | Where {$_.DeletedByName -eq "System Account"}

#Restore all deleted items matching given parameters
$Counter = 1
$DeletedItemsBySystemAccount | ForEach-Object {
    $_ | Restore-PnpRecycleBinItem -Force
    $Percentage = ($counter/($DeletedItemsBySystemAccount.count))*100
    Write-Progress -Activity "Restoring Deleted Items..." -Status "Restored File $($_.LeafName) ($Counter of $($DeletedItemsBySystemAccount.count))" -PercentComplete $Percentage

    $counter++
 }

Restore Large Number of Deleted Items and avoid Threshold Issue

When you try to restore large number of deleted items from a SharePoint Online recycle bin, you may encounter: “Restore-PnpRecycleBinItem : The attempted operation is prohibited because it exceeds the list view threshold.” issue. To avoid this issue, You can use the REST API call from PowerShell.

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/funds"

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

#Get Deleted Items from recycle bin - matching given parameters
$DeletedItemsBySystemAccount = Get-PnPRecycleBinItem -RowLimit 5000000 | Where {$_.DeletedByName -eq "System Account" -and $_.DeletedDate -gt [DateTime]"12/31/2013"}

#Restore all deleted items
$Counter = 1
$ApiCall = $siteUrl + "/_api/site/RecycleBin/RestoreByIds"

$DeletedItemsBySystemAccount | ForEach-Object {
    
    #Call the REST API Method   
    $body = "{""ids"":[""$($_.ID)""]}"
    Invoke-PnPSPRestMethod -Method Post -Url $ApiCall -Content $body | Out-Null

    $Percentage = ($counter/($DeletedItemsBySystemAccount.count))*100
    Write-Progress -Activity "Restoring Deleted Items..." -Status "Restored File $($_.LeafName) ($Counter of $($DeletedItemsBySystemAccount.count))" -PercentComplete $Percentage

    $counter++
 }

Wrapping up

In summary, restoring deleted files from the Recycle Bin in SharePoint Online using PowerShell is a straightforward process that anyone with basic knowledge of the platform and the PowerShell scripting language can perform. By using PowerShell, you can quickly and easily restore deleted files without the need to use the SharePoint Online web interface. Whether you’re a SharePoint administrator or a site owner, restoring deleted files using PowerShell is an important tool in your arsenal for managing and protecting your SharePoint Online data. With the ability to restore deleted files quickly and easily, you can help ensure that important data is never lost, even in the event of accidental deletion.

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

What is the difference between the site recycle bin and the site collection recycle bin?

The site Recycle Bin and site collection Recycle Bin are two different locations in SharePoint Online that store deleted items. The site Recycle Bin is a dedicated location on a site that stores all the deleted items and allows the user to access and restore the content if needed. The site collection Recycle Bin, also known as the second-stage Recycle Bin, is a Recycle Bin that the administrator of the site collection manages. It gives the administrator of a site collection greater control over deleted items by providing a second stage Recycle Bin. The site collection Recycle Bin can be accessed only by the site collection administrator.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

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

  • Thank you for the provided scripts. I had a few issues with them, but without them I wouldn’t have been able to get it working.

    I had to modify them a bit:

    But, the script below will restore files deleted by a user for a specfic day.

    ##Variables for Processing
    $SiteUrl = “SharePoint URL of the site”
    $DeletedByUserEmail = “User Email address”
    $DeletedDate = “2023-05-11” # Specify the date in “YYYY-MM-DD” format
    $BatchSize = 200 # Number of items to retrieve in each batch

    # Load SharePoint DLLs
    Add-Type -Path “C:\Program Files\WindowsPowerShell\Modules\PnP.PowerShell\2.1.1\Core\Microsoft.SharePoint.Client.dll”
    Add-Type -Path “C:\Program Files\WindowsPowerShell\Modules\PnP.PowerShell\2.1.1\Core\Microsoft.SharePoint.Client.Runtime.dll”
    Add-Type -Path “C:\Program Files\WindowsPowerShell\Modules\PnP.PowerShell\2.1.1\Core\Microsoft.SharePoint.Client.Search.dll”

    #Connect to SharePoint Online
    $credentials = Get-Credential
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credentials.UserName, $credentials.Password)

    Try {
    #Get the Site recycle bin
    $RecycleBinItems = $Ctx.Site.RecycleBin
    $Ctx.Load($RecycleBinItems)
    $Ctx.ExecuteQuery()

    # Create CAML query to retrieve items deleted by a specific user on the given date
    $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $camlQuery.ViewXml = @”

    $DeletedByUserEmail

    $DeletedDate

    $BatchSize

    “@

    $itemsProcessed = 0

    # Retrieve items in batches using pagination
    do {
    $items = $RecycleBinItems | Where-Object { $_.DeletedByEmail -eq $DeletedByUserEmail -and $_.DeletedDate.Date -eq $DeletedDate }
    foreach ($item in $items) {
    $item.Restore()
    Write-Host “Restored Item:” $item.LeafName
    }

    $itemsProcessed += $items.Count
    } while ($items.Count -gt 0)

    Write-Host “Total Number of Items Deleted by User on the given Date:” $itemsProcessed
    }
    catch {
    Write-Host “Error: $($_.Exception.Message)” -ForegroundColor Red
    }

    Happy scripting…

    Reply
  • #threshold – sulosion
    $Location = Split-Path $psISE.CurrentFile.FullPath ; Push-Location $Location
    $SiteURL = “https://#####.sharepoint.com/sites/NB-AP-JK-FinAP”

    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -UseWebLogin -WarningAction Ignore

    $EraserUser = Get-PnPRecycleBinItem | Select Title, DirName, ItemType, DeletedByEmail, DeletedDate, ItemState, id | Where { $_.DeletedByEmail -eq “Wenrong.Li@###.com”}
    $EraserUser | Export-csv Wenrong.csv -Delimiter ‘,’ -Encoding Unicode
    #$EraserUser.Count
    #$EraserUser | select -First 50

    $EraserUsers = $EraserUser.Id.Guid
    #$EraserUser.Id.Guid | Select -First 5 #Test

    foreach ($id in $EraserUsers)
    {
    Invoke-PnPSPRestMethod -Method Post -Url “https://#####.sharepoint.com/sites/NB-AP-JK-FinAP/_api/site/RecycleBin/RestoreByIds” -Content “{“”ids””:[“”$Id””]}” | Out-Null
    Write-Host $id -ForegroundColor Cyan
    }

    #https://github.com/pnp/PnP-PowerShell/issues/2315
    #https://cann0nf0dder.wordpress.com/2020/02/13/viewing-restoring-and-removing-items-from-the-sharepoint-recycle-bin-the-attempted-operation-is-prohibited-because-it-exceeds-the-list-view-threshold-enforced-by-the-administrator/

    Reply
  • 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 “salaudeen@crescent.com”} | 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 *