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 this 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.

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 users email address, but you could also use the field DeletedByName

Filter on file type

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

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.