Restore Recycle bin SharePoint Online with PowerShell

One of my users deleted a complete 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:

$web = Get-PnPWeb
$ctx = Get-PnPContext

$Context.Load($Web)
$Context.Load($RecycleBinItems)
$Context.ExecuteQuery()

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.

Install-Module SharePointPnPPowerShellOnline

When done, we can connect to the SharePoint site in question. We are adding -interactive for the MFA authentication.

Connect-PnPOnline -Url https://contoso.sharepoint.com/teams/team1 -Interactive

Retrieving the items from the Recycle bin

Before we start, let’s first check if there are any items in the recycle bin at all:

(Get-PnPRecycleBinItem).count

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 than 0, 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.

# Set the restore date to yesterday
$today = (Get-Date)
$restoreDate = $today.date.AddDays(-1)

# Get all items that are deleted yesterday or today, select the last 10 items and display a list with all properties
Get-PnPRecycleBinItem | ? $_.DeletedDate -gt $restoreDate | select -last 10 | fl *

Find files between dates

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

$today = (Get-Date) 
$dateFrom = $today.date.addDays(-11)
$dateTo = $today.date.addDays(-10)

Get-PnPRecycleBinItem | ? {$_.DeletedDate -gt $dateFrom -and $_.DeletedDate -lt $dateTo}  | select -last 10 | fl *

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

Get-PnPRecycleBinItem -FirstStage | ? DeletedByEmail -eq 'john@contoso.com'

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

Get-PnPRecycleBinItem | Where-Object {($_.DeletedDate -gt $dateFrom -and $_.DeletedDate -lt $dateTo) -and ($_.DeletedByEmail -eq $deletedByUser)}  | Select-Object -last 10 | ft *

Filter on file type

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

Get-PnPRecycleBinItem -FirstStage | ? LeafName -like '*.docx'

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 kinds of filters on the recycle bin items.

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

Get-PnPRecycleBinItem | ? Title -Like '*test*' | ft

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:

 Get-PnPRecycleBinItem | ? {($_.Title -like '*test*') -and ($_.ItemType -eq 'File')} | ft

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.

Get-PnPRecycleBinItem | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq 'john@contoso.com')} | Export-Csv c:\temp\restore.csv

Restoring the files

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

Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq 'john@contoso.com')} | Restore-PnpRecycleBinItem -Force

Complete Scripts

I created a small script that allows you to restore files easily from the recycle bin using two dates and a user email address as a filter. You can also find this script here in my GitHub repository.

# SharePoint site URL:
$spUrl = ""

# Connect to SharePoint
Connect-PnPOnline -Url $spUrl -Interactive 

# Set the restore date to x days in the past
$today = (Get-Date) 
$dateFrom = $today.date.addDays(-11)
$dateTo = $today.date.addDays(-10)

# Set user to find files from
$deletedByUser = ""

# Show dates
write-host "Finding files from $dateFrom to $dateTo" -ForegroundColor Cyan

# Get all items that are deleted x days ago, select the last 10 items and display a list with all properties
Get-PnPRecycleBinItem | Where-Object {($_.DeletedDate -gt $dateFrom -and $_.DeletedDate -lt $dateTo) -and ($_.DeletedByEmail -eq $deletedByUser)}  | Select-Object -last 10 | ft *

# Confirm test results
$confirmation = Read-Host "Are the result as aspected? [y/n]"
if ($confirmation -eq 'y') {
  # Proceed
  Write-Host "Restoring items" -ForegroundColor Cyan

  Get-PnPRecycleBinItem -firststage | 
    Where-Object {($_.DeletedDate -gt $dateFrom -and $_.DeletedDate -lt $dateTo) -and ($_.DeletedByEmail -eq $deletedByUser)} | 
    Restore-PnpRecycleBinItem -Force

  Write-Host "Restore completed" -ForegroundColor Green
}

Jose (see comments below) created a script that will recursively restore a complete folder from the recycle bin when you have too many items in your recycle bin.

When you have too many items in your recycle bin you can get the list limit error: “The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator”, preventing you from restoring the files.

You can find his script here at GitHub, make sure you check it out. As with all scripts, use it at your own risk!

Restore-RecycleBin function

Another reader also created a complete script to restore files from the recycle bin and wrapped it into a nice function.

You can find the complete script from George here on his GitHub.

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

  1. Use with extreme caution!!! You risk losing all your date during restore process due to security restrictions of your particular organization.

    We recently moved our Business unit’s servers to SharePoint. OneDrive attempted to sync the new SharePoint to my OneDrive on my laptop, 800 GB worth. I had stopped syncing on OneDrive, deleted the SharePoint folder/link on my laptop, and restarted the syncing on OneDrive. One drive asked after comparing folders on Cloud vs. Laptop, detected the deletion and requested to delete folder in Cloud. I clicked yes not knowing the folder was not a copy of the SharePoint folder/server. I ended up deleting half the server.

    After having to Click yes to restore over 50x with no end in sight, I found this site and proceeded to follow instructions. I thought best that I test on my personal data to make sure it worked properly, 42 GB’s worth. The script appeared to work perfectly restoring the folder to OneDrive.

    I proceeded to attempt the restoration of the SharePoint folder/server data. After several attempts to restore and getting Access denied. I decided to open my personal folder to check for something, data was not actually in personal folder, nor was it in the recylebin. Had security not blocked my attempts I could have potentially could have lost 600 GB worth of data on the server.

    Soo..being thankful that the IT gods had decided protect me from my own stupidity, I went through the process of manually restoring the files on the server. After clicking 10x more and only being able to select 50 folder contents at a time, I downloaded Autoclicker.exe to automate the process since there were not any other options. 8 hours later the everything finally restored.

    • I have used this script in a large environment as well, without any issues. Not sure what really happened in your case when you tried to restore the data from your OneDrive recycle bin. Hard to say if it’s a problem with the script or maybe something else.

  2. very helpful. I got an error “Get-PnPRecycleBinItem: The request message is too big. The server does not allow messages larger than 2097152 bytes.” when trying to restore over 5000 items. This is separate to the max list error some people are experiencing. I got around it by just restoring 1000 items at a time
    Get-PnPRecycleBinItem | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq ‘user@domain.com’)} | select -last 1000 | Restore-PnpRecycleBinItem -Force

  3. I had a few issues with this and after trying to restore a bunch of files over the limit that Sharepoint allowed I contacted Microsoft after about 3-4 days we ended up installing this.

    https://github.com/abrcheng/SharePointOnlineQuickAssist

    I was a little funny about it to start with but it was actually written by one of the staff at Microsoft in the Sharepoint team. I must say I have used it a few times now and even had it adjusted as it was having timeout issues with 200 batches so it was changed to 10 at a time and it just cycles through. Works really well. Worth the install if you are doing this kind of thing a bit.

  4. I just used Georges script linked at the bottom of this article, along with NickDK’s comments/pointers from May2022 to successfully restore 100,000+ items. Thank you for helping me save the day for my customer!!

  5. Thank you for this!

    I have successfully restored 1,048,574 files/folders that a user accidentally deleted while trying to remove a “shortcut” from his OneDrive folder.

    Notes:
    – I used George’s script, linked above. I specified all variables (both dates, the email, and I set “maxRows 99999999”).
    – My account is a “Site Collection Administrator” (not a Global Admin or SharePoint Admin)
    – I modified the connect command to the following: “Connect-PnPOnline -Url $siteUrl -UseWebLogin -WarningAction Ignore”
    – Processing my restore list took so long that my connection timed out before the API calls began, so I also copied the same “Connect-PnPOnline” command and inserted it immediately before the “while($leftToProcess -gt 0)” loop.
    – The script ran for about 36 hours and seemed to complete successfully, however, I ran the script a second time and it found a few hundred more files in the the date range I had input, so I’m not sure why they were missed in the first pass. A third run of the script did not find any additional files to restore from the date range specified.

  6. Hi,

    Any updates to this with the new PowerShell commands and newer PowerShell instances, I am having issues getting this to work now.

    • What error’s are you seeing (Granted I haven’t run the script in a while)? I just looked at the post from April and it looks like a permission issue there. Even though the users are administrators, feature might not be installed or enabled like PNP Powershell.

      • Hi Jose,

        I had those issue fixed back then, just noted recently when attempting to run the commands come of the commands had changed in Powershell, got it sorted after about 30 minutes of fighting with PS. But can’t remember exactly what I did. But with MFA and the modern auth requirements now I was having to use Connect-PnPOnline -Url $SP_URL -UseWebLogin

  7. Hi guys, it appear I can get the 2 files I need to restore, but the script isn’t able to restore them.
    This is the error:

    PS /Users/lol/Downloads> ./restore.ps1
    2
    Building statement to restore the following 2 files
    Adding File : sites/ConlegnoIntranet/Documenti condivisi/Work/SPEDIZIONI/DISTINTE INVIATE/2021/02_Febbraio/05-02-2021 // cdc del 05-02-2021.xlsx
    Adding File : sites/ConlegnoIntranet/Documenti condivisi/Work/SPEDIZIONI/DISTINTE INVIATE/2021/02_Febbraio/05-02-2021 // distinta del 05-02-2021.xlsx
    {“ids”:[“acfcc7b7-cde9-4a17-9ca9-30d0d320f914″,”45391b17-61cc-476f-b14a-000c5eb9066d”]}
    Performing API Call to Restore items from RecycleBin…
    Invoke-PnPSPRestMethod: /Users/lol/Downloads/restore.ps1:39
    Line |
    39 | Invoke-PnPSPRestMethod -Method Post -Url $apiCall -Content $b …
    | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | {“odata.error”:{“code”:”-2147024809, System.ArgumentException”,”message”:{“lang”:”it-IT”,”value”:”ids”}}}

    Any hints?

  8. Thanks for the great post with links to the other git items. Made me look like a hero when a user deleted a synched folder of some thousands of shared files.

  9. Hello and many thanks for sharing! This has helped loads.
    Regarding the script, I had 2 questions.
    .
    if a user has deleted all the content from a “Document Library”. (lets call it “clients”)
    – What is the “$directoryToRestore” path?

    i.e is it $directoryToRestore = ‘root/clients/’

    Second: to filter for the user and dates – Are we just including the variables into the “$RestoreSet”?

    i.e.
    ————-
    $restoreSet = Get-PnPRecycleBinItem -FirstStage -RowLimit $maxRows | Where-Object {($_.”Dirname” -Like $directoryToRestore + ‘/*’ -or $_.”Dirname” -Eq $directoryToRestore) -and ($_.DeletedDate -gt $date2 -and $_.DeletedDate -lt $date1) -and ($_.DeletedByEmail -eq ‘user@contoso.com’)}
    ————

    Hope this makes sense.

    Thank you!

  10. I’m trying this and receiving the following Invoke-PnPSPRestMethod : Object reference not set to an instance of an object.

    At C:\RecycleRestore.ps1:102 char:13
    + Invoke-PnPSPRestMethod -Method Post -Url $apiCall -Conten …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Invoke-PnPSPRestMethod], NullReferenceException
    + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Admin.InvokeSPRestMethod

  11. Any hint on how to face the exception “A file with the same name already exists”…?
    I would like to replace the existing files/folders.
    Thanks for any help!

    • In my function, I shrank the batch size as I re-ran the procedure. Eventually I ran with a batch size of 1 and ignored all the same name items.

  12. This is an excellent resource! I’m trying to use it to help a client who has deleted large numbers of files on several occasions.

    I’m trying to use George’s function, and it works great until the api call to actually restore the data, which it fails with Invoke-PnPSPRestMethod : {“odata.error”:{“code”:”-2147024891, System.UnauthorizedAccessException”,”message”:{“lang”:”en-US”,”value”:”Access denied. You do not have permission to perform this action or access this resource.”}}}
    At C:\redacted\Powershell Scripts\restoresharepointdata.ps1:112 char:13
    + Invoke-PnPSPRestMethod -Method Post -Url $apiCall -Conten …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Invoke-PnPSPRestMethod], Exception
    + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Admin.InvokeSPRestMethod

    I’ve tried running this with several users who are global admins, but it doesn’t work. Anyone else run into this before?

    Thanks in advance!

      • Good question, hadn’t thought of that, though, unfortunately, (?) the accounts are licensed for sharepoint. It’s like the user accounts don’t have access to the api, but I can’t find how to grant api access to an account rather than an application.

    • Are you working from scratch per the article or starting from Jose’s or my scripts? As Jose requested a copy of what you’re working from would help.

    • Jose’s API call was the brilliant touch that made restoring several hundred thousand items in a site library feasible within a short time frame. I made the max Rows returned and Batch Size a variable. and it chewed through huge chunks in no time at all.

    • Should also note, it appears the API fails an entire batch if one of the items to restore in the batch errors for any reason. I parameterized the $batchSize variable and progressively stepped from batches of 500 to 100, 10 and finally 1 item at a time.
      In my case the client started to manually recover items into a few locations using documents they had on hand.

      • Glad the script helped. I noticed this was an issue also, if a file existed would fail the job. I thought about just writing a small GUI app to just connects via the Microsoft Graph API. Something, you could OAUTH into the drive and then use a GUI front end to make it much easier to restore and set options like replace or ignore existing, especially with this library limit that is giving us a headache. Maybe if things slow down I might have the time to write the app. 🙂

        • Slow down? Too often I feel like the old “I’ll rest when I’m dead”. I keep thinking I’m in the wrong industry.

  13. Just wanted to say thank you. Client had too many files in the recycle bin to try to scroll through and recover. I tried to use Restore-PnpRecycleBinItem but due to the recycle bin having over 400K items and getting the list limit error, I had to resort to the API. I ran into the problem where if I used the API script as it was, it would only recover some files or folders, some failing because the parent folder was still missing. So I had to sort the folders. This is part of the script to recursively restore an entire folder and everything inside of it.

    Hope it helps if you run into my situation.

    # Defines the folder
    $directoryToRestore = “rootfolder/thisfoldertorecover”
    # Get files where the folder applies requires two search conditions
    # RowLimit of 400000 Used because there were approximately 390000 items in Recycle Bin – you can adjust depending on your item count
    $restoreSet = Get-PnPRecycleBinItem -RowLimit 400000 | Where-Object {$_.”Dirname” -Like $directoryToRestore + ‘/*’ -or $_.”Dirname” -Eq $directoryToRestore}
    # Sorts so it recovers the folder(s) so the sub folders/files recover correctly
    $restoreSet = $restoreSet | Sort-Object -Property @{expression =’ItemType’; descending = $true},@{expression = “DirName”; descending = $false} , @{expression = “LeafName”; descending = $false}
    If someone thinks they might want the full script, let me know and I can post it.

  14. The solution to the error “The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.” is to use the -RowLimit 40000 command like this:
    Get-PnPRecycleBinItem -RowLimit 50000 | Where {($_.DeletedDate -gt $date2 -and $_.DeletedDate -lt $date1) -and ($_.DeletedByEmail -eq ‘ssss@aaa.com’)} | Export-Csv c:\temp\recyclebinreport.csv

  15. This would be great except for the error “The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.”
    Does anyone have a solution that works? Please help! I’ve tried all of the above options but nothing gets past that error even the limit to just the last 10 items.

  16. I tried to run:
    Get-PnPRecycleBinItem | ? {($_.DeletedByEmail -eq ‘xxxx@xxxx.net’)} | Restore-PnpRecycleBinItem -Force

    and got a lot of file already exists error, e.g.

    Restore-PnpRecycleBinItem : A file with this name “MRSTX050632.kml” already exists in “Shared Documents/Projects/xxxx/MRSTX0499”. To restore the file, rename the existing file and try again.
    At line:1 char:89
    + … xxxx@pxxxx.net‘)} | Restore-PnpRecycleBinItem -Force
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Restore-PnPRecycleBinItem], ServerException
    + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.RecycleBin.RestoreRecycleBinItem

    How do I skip the existing files?

  17. You could filter by the date range then output the result to Out-GridView.
    Then you have a GUI for easy change the finer filter

    Get-PnPRecycleBinItem | ? { $_.DeletedDate -gt $date2 -and $_.DeletedDate -lt $date1} | Out-GridView

  18. Great Article.
    I’m having to do a restore after a move of documents from one site to another failed. It left some files and folders in one site and the rest in another. When using the GUI to restore we’re seeing an error about files and folders already existing in the restore location. Is there a filter/switch to add to the command that allows you to keep both copies.

    • Most of the time you can ignore the error. When you are restoring SharePoint items, it will go through a list of items:

      \folder1\file1
      \folder1\file2
      \folder1

      It starts with file 1, and to restore it, it will create folder1. At a given point, it will come to the folder itself, but then it already exists. Now, this won’t go up for files, but the error about the folder you can most of the time just ignore.

      About the switch, there is non that I am aware of.

  19. If you are receiving this message: The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.

    There is no way around it, there is no solution for it, none of the suggestions work.

    • I seem to have similar results and getting the dreadful error “The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator” when trying to restore by unique id:
      Restore-PnpRecycleBinItem -Identity c09x43961-d9a3-4293-bc9a-948y4422b67c.
      I get the same error when executing the code which is behind the pnp cmdlet, so this is nothing to do with the cmdlet itself:
      var item = bin.GetById(itemUniqueId);
      item.Restore();
      clientContext.ExecuteQueryRetry();

      Could this be tenant specific? Maybe MS forgot to index the recycle bin for the older ones?

  20. 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!

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

  22. 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/user_name@emailaddress.com

    (Get-PnPRecycleBinItem).count

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

    Get-PnPRecycleBinItem | ? { ($_.DeletedByEmail -eq ‘user_name@emailaddress.com.au’)} | Restore-PnpRecycleBinItem -Force

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

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

    • And if you add the deletedbyEmail part?
      Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq 'john@contoso.com')} | Restore-PnpRecycleBinItem -Force

  24. 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 ‘my.email@company.com’)} | 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.

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

  26. 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?

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

  28. 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…

    • You should be able to restore the items in smaller batches. You can’t change the List View threshold, it’s limited to 5000. So what you could do is add | select -last 5000.

  29. Hi I tried to run the command Get-PnPRecycleBinItem -firststage | ? {($_.DeletedDate -gt $restoreDate) -and ($_.DeletedByEmail -eq ‘myuser@domain.com’)} | 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!!

  30. 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 ‘myuser@domain.com’)} | 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.

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

  32. 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?

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

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

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

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

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

0 Shares
Tweet
Pin
Share
Share