office-365-advent-calendar

Scenario

You’ve got a big amount of items in the recycle bin of a site which you want to access. For example, a user accidentally deleted hundreds of files, and now you want to restore them back easily. Or you have a thousand items in the recycle bin and you want to export some information (which items are in the recycle bin, who deleted them and when) to Excel

Code

Once again, we’re using the PnP PowerShell cmdlets here as a basis, but then also make use of the underlying CSOM calls to access the recycle bin.

$cred = Get-Credential
#Set URL to the web for which you want to retrieve the recycle bin
Connect-PnPOnline -Url https://mytenant.sharepoint.com/sites/departmentsite -Credentials $cred

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

#Loading the Recycle Bin Items
$recycleBin = $web.RecycleBin
$ctx.Load($recycleBin)
$ctx.ExecuteQuery()

#We are now narrowing down the items. We only want to restore all Excel spreadsheets
$spreadsheets = $recycleBin | Where {$_.Title -like "*.xlsx"}

#Another example: select all items deleted by a specific user
#$deletedByUser = $recycleBin | Where {$_.DeletedByEmail -eq "rene@mytenant.onmicrosoft.com"}
#Restoring the spreadsheets
$spreadsheets | %{ $_.Restore() }
$ctx.ExecuteQuery()

#Exporting all items to a CSV file
$recycleBin | Select Title, DeletedByEmail, DeletedDate | Export-Csv C:\RecycleBinItems.csv

Example of a CSV export:

TitleDeletedByEmailDeletedDate
Project_Template.pptxrene@mytenant.onmicrosoft.com12/3/2016 1:19
Azure_Information_Protection_licensing_datasheet_EN-US.pdfrene@mytenant.onmicrosoft.com12/3/2016 1:20
Security in Office 365 Whitepaper.docxrene@mytenant.onmicrosoft.com12/3/2016 1:20

If you are curious which methods and properties are available for the recycle bin in general as well as individual items, please review RecycleBinItemCollection and RecycleBinItem.

One thought on “Office 365 Advent Calendar – 03 Programatically accessing a SharePoint Online Recycle Bin”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.