Find who deleted files in SharePoint Online using PowerShell PnP (from the recycle bin)

Recently, I have seen a few requests about how can we get who deleted files in a SharePoint Online site? You know, that “Deleted by” column in the recycle bin?

But have you tried to get the value of that column with PowerShell PnP? Of course you have, by using the DeletedBy property of Get-PnPRecycleBinItem
And have you noticed something like… blank results? 😟

Well, I’ve stumbled on that too! Some CSOM objects are not returned (blank) and this is not an easy fix, BUT changes might come in the future. So for now, we can use the following workaround! 😉

The user details

Connect to your site using Connect-PnPOnline and then we’ve got the usual suspects (for example) with $results = @() to store our results, and a foreach loop for all the items in the recycle bin.
The important part in the script is how do we get the user name, or (like I’ve seen being asked) the user ID?? 🤔

Looking at the below script, I can get the name of the user with $item.DeletedByName

Connect-PnPOnline -Url "https://<TENANT-NAME>.sharepoint.com/sites/<YOUR-SITE>" -Credentials <YOUR-CREDS>

$allDeletedItems = Get-PnPRecycleBinItem
$results = @()

foreach($item in $allDeletedItems){
    
    $results += [pscustomobject]@{
        fileName = $item.LeafName
        deletedBy = $item.DeletedByName
        deletedDate = $item.DeletedDate    
    }
}
$results

If the username is all you’re interested in, you can stop here.
But if you’re looking at the user ID, then read on!

 

Find the user ID

Spoiler: We’re going to do a little bit of match-making here  😇  But I promise it’ll be quick. Why? Because we have a very useful cmdlet called Get-PnPAzureADUser.
So, we’ll use the $item.DeletedByName and match that value to the DisplayName property we get with Get-PnPAzureADUser. All between parenthesis to get the .Id value!

 

Connect-PnPOnline -Url "https://<TENANT-NAME>.sharepoint.com/sites/<YOUR-SITE>" -Credentials <YOUR-CREDS>

$allDeletedItems = Get-PnPRecycleBinItem
$results = @()

foreach($item in $allDeletedItems){
    $userID = (Get-PnPAzureADUser | Where-Object {$_.DisplayName -match $item.DeletedByName}).Id
    
    $results += [pscustomobject]@{
        fileName = $item.LeafName
        deletedBy = $item.DeletedByName
        deletedDate = $item.DeletedDate
        userID = $userID
    }
}
$results

There we have it!

 

Hope it helps. Thanks for reading!

 

 

 

Leave a Reply

%d bloggers like this: