Restore Recycle bin SharePoint Online with PowerShell

One of my users deleted a whole document library containing more than 12000 items. He synced the folder to his desktop, to find out it was way too big. Unfortunately, he deleted the items from his desktop without stopping the synchronization first. You can restore items from the recycle bin in SharePoint Online, but these many items can easier be done with PowerShell.

I did some searching on the internet to find a solution and found a few using PnP-Context:

But this didn’t return any result if I run $recycleBinItems.count the result was 0. Finally, I found a post from Farook Khan who had a similar issue and used PnP-RecycleBinItem. With this many items, I want an overview before I restore it. Also, I wanted to add some filters, like date and user.

Connecting to SharePoint

So to get started we need to install the PnP PowerShell module if you don’t have it already.

When done, we can connect to the SharePoint site in question.

Retrieving the items from the Recycle bin

Before we apply any filter, let’s just check if there are any items in the recycle bin at all

You can add -firststage or -secondstage after Get-PnPRecycleBinItem. The first stage recycle bin is the one you see when you navigate in SharePoint to recycle bin. The Second stage is the one you will see when you scroll to the bottom of the first stage and select Check the second-stage recycle bin.

SharePoint online recycle bin with Second-level link highlighted

So if the count returned more then 0, when we can continue filtering the list to select only the items we need.

Filter on date

Deleted items are retained for 93 days in the recycle bin, so filtering on the date is a good thing to do. In my case, the user deleted the items yesterday. To test the query I select only the last 10 items and show them in a list with all properties.

Find files between dates

Juan asked if it’s possible to restore the files between two specific dates. And yes that is possible. I added two dates, date1 is the one closest to now and date2 is one longest ago. We can create a filter where we select the files that are older then date2 and younger then date1:

Filter on user

You can also filter the result on the user who deleted the items.  I added the first-stage recycle bin filter here and used the user’s email address, but you could also use the field DeletedByName

If you want to combine both date and user as a condition you will have to wrap both conditions between round brackets.

Filter on file type

Another common case is that you want to restore a specific file type.

Search a specific file on a filename

Mike asked if it is possible to find a specific file in the recycle bin. Because we are using PowerShell we can use all kind of filters on the recycle bin items.

Use the -like operator to search on a part of the filename. Add * as a wildcard marker in the filename.

An exact file can be found by using the -eq operator.

Searching the recycle bin on a filename will also return folders that contain, a part of, the name. So you might want to add another condition to get only the files:

Export results to CSV

In the case of a large set of files that need to be restored is it always good to double check what you are restoring. The easiest way is to export the results of the quest to a csv file so you can review everything.

Restoring the files

If you are happy with the filter then you can start restoring the items from the recycle bin.

 

Get more stuff like this

IT, Office365, Smart Home, PowerShell and Blogging Tips

I hate spam to, so you can unsubscribe at any time.

41 thoughts on “Restore Recycle bin SharePoint Online with PowerShell”

  1. This is great! Thanks a lot. I have a similar case where we delete a bunch of unused data from time to time (number of files is 100k+). Sometimes our users realize that it would be good to have something back in which case we (IT Team) lose a lot of time restoring it manually.

    Would it be possible to specify the folder what to restore (full path or similar)? In most cases, our users know the exact folder where the data was stored.

    Thank you!

  2. Hello again,

    So a colleague and I managed to get this to work. Basically, PowerShell seems good at forgetting credentials really quickly, so we parsed these in via some variables and a reconnect command. Here’s our code:

    $UserName = Read-Host -Prompt ‘Input the users email address’
    $SP_User = read-Host -Prompt ‘Input the user name from the onedrive URL’
    $SP_URL = “https://my-business.sharepoint.com/personal/” + $SP_User + “_mycompany_com”
    $User_Cred = Get-Credential

    #install required modules

    Try{
    Import-Module SharePointPnPPowerShellOnline
    }
    Catch
    {
    Install-Module SharePointPnPPowerShellOnline
    }

    #connect to the OneDrive Store

    Connect-PnPOnline -Url $SP_URL -Credentials $User_Cred

    # check to see what’s in recycle bin

    (Get-PnPRecycleBinItem).count

    ##############

    ## Logging: ##

    # Export results to a .csv (in other words, create a log of the output)

    Get-PnPRecycleBinItem | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq $UserName)} | Export-Csv “c:\$UserName restore.csv”

    ##############

    # Start the restore:

    # Restore from the First Stage Recycle Bin:

    Connect-PnPOnline -Url $SP_URL -Credentials $User_Cred

    Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq $UserName)} | Restore-PnpRecycleBinItem -Force

    # Restore from the Second Stage Recycle Bin:

    Connect-PnPOnline -Url $SP_URL -Credentials $User_Cred

    Get-PnPRecycleBinItem -secondstage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq $UserName)} | Restore-PnpRecycleBinItem -Force

    $User_Cred = $null

  3. Thanks for the reply!

    Just to confirm, when I’m authenticating as end user, the script will either:
    (a) complete the count, create the .csv log of files, and then stop with the below error:

    Get-PnPRecycleBinItem : User cannot be found.
    At line:9 char:1
    + Get-PnPRecycleBinItem | Restore-PnpRecycleBinItem -Force
    + ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Get-PnPRecycleBinItem], ServerException
    + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.RecycleBin.GetRecycleBinItems

    or, if I COMMENT OUT the logging line:
    (b) it will execute and the restore will successfully complete, but there will be no log file.

    I can’t seem to get both to happen at once, regardless of where or how I try to incorporate | export-csv into the command line.

    My code is:

    Install-Module SharePointPnPPowerShellOnline

    Connect-PnPOnline -Url https://my-TenantName.sharepoint.com/personal/[email protected]

    (Get-PnPRecycleBinItem).count

    # Get-PnPRecycleBinItem | Export-Csv c:\temp\OneDrive-restore.csv

    Get-PnPRecycleBinItem | ? { ($_.DeletedByEmail -eq ‘[email protected]’)} | Restore-PnpRecycleBinItem -Force

    But this isn’t a huge deal – because I can always run the script twice 🙂

  4. Currently trying to run this command but getting the “User Cannot Be Found” error when doing the actual restore. I can get the Count and the list of files that will be restored, but it errors out during the actual restore. The account I’m using is a Site Collection Admin on the site and a Global Admin.

    #gets the count

    (Get-PnPRecycleBinItem).Count

    #Set Dates

    $today = (Get-Date)
    $restoreDate = $today.date.AddDays(-6)

    #Restores

    Get-PnPRecycleBinItem -FirstStage | ? {$_.DeletedDate -gt $restoreDate} | Export-CSV “c:\Users\Christine Chandler\Desktop\Restore_Items_04112019.csv”
    Get-PnPRecycleBinItem -FirstStage | ? {$_.DeletedDate -gt $restoreDate} | Restore-PnpRecycleBinItem -Force

  5. Hello! Firstly, wonderful page!

    I’m trying to run this script to automatically restore a customer’s Onedrive for Business (O365) Recycle Bin contents. When I test it on my own account, the count part completes , and lists the number of recycle bin items. However, then I get:

    Get-PnPRecycleBinItem : User cannot be found.
    At line:86 char:1
    + Get-PnPRecycleBinItem | Restore-PnpRecycleBinItem -Force
    + ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Get-PnPRecycleBinItem], ServerException
    + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.RecycleBin.GetRecycleBinItems

    My command is simply:
    # Get-PnPRecycleBinItem -firststage | select -last 5000 | Restore-PnpRecycleBinItem -Force

    Also, before hitting this line, I’m running:

    Get-PnPRecycleBinItem | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq ‘[email protected]’)} | Export-Csv c:\temp\restore.csv

    And this is also working. There’s only 104 items, so it’s not hitting any limits.

    Do I need to use Get-PnPRecycleBin -Identity with a GUID?
    (note: I’m not a global admin – perhaps that’s why it’s failing?).

    thanks in advance!

    • You will have to be an admin of the tenant to restore other users Onedrive content. Try authenticating with the users account if possible or user the global admin of the tenant.

  6. Yes. Global Admin of Office 365. The only thing that may make it a bit more unique is that it is actually a “Team Site”. It was created via the Teams app and not straight from Sharepoint.

    I tried all manor of scripts last night. PowerShell, some client.dll call from the SDK. No matter what when each went to execute the query against the recycle bin they failed with a limits error.

  7. Ruud,
    This seem to be exactly what I am looking for, however just like the others, I am getting the error “The attempted Operation is prohibited because it exceed the list view threshold…”

    I have a recycle bin of approximately 150K items and I need to restore most of them.

    It seems to be the Get-PnPRecycleBinItem command that is causing it, I have try to pipe that in to any number of filters from -last 100 to a file name specific query and they all result in the same error.

    Any thoughts would be greatly appreciated.

    • Darren, I haven’t figured it out yet. During my recovery, I was able to restore more than 10.000 items. Are you a global admin in Office 365 / SharePoint?

  8. Even with using “select -last 100” I still get the “The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator” can’t seem to find a way around this for the recycle bin.

  9. It drives me crazy but I can’t find a way to make it work. I have 100,000+ deleted files in the recylcebin. So I managed to receive all the IDs from the deleted files. But when I’m trying to run the following command:

    Restore-PnpRecycleBinItem -Identity ‘78259039-1010-4786-8abe-c829c60ea940’ -Verbose

    Restore-PnpRecycleBinItem: The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.

    I can’t find any way to restore a single document from the recycle bin…

  10. Hi I tried to run the command Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq ‘[email protected]’)} | Restore-PnpRecycleBinItem -Force

    I got the error message: The attempted operation is prohibited because it exceeds the list view threshold enforce by administrator.

    Need help bro!!

  11. Ruud any word on recyclebin size threshold, see below the error, i got a very big recycle bin, but can not list nor restore because of this

    Get-PnPRecycleBinItem : The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.
    At C:\Hitachi_dev\Restore-RecycleBin.ps1:16 char:2
    + (Get-PnPRecycleBinItem).count

    • I am trying to reproduce the error on my side, but with 5500 items is still works. What if you try to limit the results in chunks of 5000?

      Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq ‘[email protected]’)} | select -last 5000

      If it’s not working, can you give me more details about the size of the deleted items? So I can try to reproduce the error here.

  12. Brilliant!! Thank you for writing this! Someone in work deleted 12,000+ files by accident (apparently) and I just used this to restore them from the recycle bin.

    Note: I also saw the “Get-PnPRecycleBinItem : The request message is too big.” error but when I just tried the command again it worked without complaining.

  13. Great tutorial and very informative. I am trying to use it now to bulk restore files but getting this error:
    Get-PnPRecycleBinItem : The request message is too big. The server does not allow messages larger than 2097152 bytes.
    At line:1 char:1
    + Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $date2 -an …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Get-PnPRecycleBinItem], ServerException
    + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.RecycleBin.GetRecycleBinItems

    Cmd used was:
    Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $date2 -and $_.DeletedDate -lt $date1) -and ($_.DeletedByEmail -eq ‘***@***.com’)} | Restore-PnpRecycleBinItem -Force

    Previous commands to export list to csv worked and produced 7500 results. Is there a limit to the restore command?

  14. awesome stuff, helped a lot.
    Now, is there a way to restore to a different site?, or to download all the recyclebin files-folders?

  15. I tried to restore some files and got error:

    Get-PnPRecycleBinItem : The request message is too big. The server does not allow messages larger than 2097152 bytes.
    At line:1 char:1
    + Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDa …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Get-PnPRecycleBinItem], ServerException
    + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.RecycleBin.GetRecycleBinItems

    • Sure, you can use a where statement to filter the results not on a date, but on a filename.

      Use -Like to search on a part of the filename.
      Get-PnPRecycleBinItem | ? Title -Like ‘*test*’ | ft

      If you want an exact match, then you can use -eq ‘test file 01.pdf’ for example.

  16. Hello,

    I dont get any output when i try to search for date and user. it works if i do it apart. but together it would work. i get error that DeletedDate is not recognized as a know commando.
    And if i use your example for the csv export its empty.

    Please some help

  17. Thank you very much for the examples, very handy!!

    I was wondering how to proceed with conflict resolution in a case where we would want to force overwrites?

    Restore-PnpRecycleBinItem : A folder with this name “asdasd” already exists in “sites/asdasd/qweqwe”. To restore the folder, rename the existing folder and try again.
    At line:1 char:10
    + $files | Restore-PnpRecycleBinItem -Force;
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Restore-PnpRecycleBinItem], ServerException
    + FullyQualifiedErrorId :
    EXCEPTION,SharePointPnP.PowerShell.Commands.RecycleBin.RestoreRecycleBinItem

    • I just created a test case to check this behavior and I get the same error. But as I can remember, the files are actually restored. Also in the test that I just did al the files are restored.

      So you can ignore the error.

  18. One of the best, most succinct and to the point articles I’ve read in ages. It’s useful, specific and the examples just work.
    Thank you.

Leave a Comment