Is there a powershell command to delete permanently all deleted users from Microsoft 365?

Viewed 65

I have 500 users in my deleted items, I can not wait for them to be delete after one month, I can not also select them one by one in Azure active directory to delete them. I would like to delete all the content at once.

1 Answers

Install the microsoft.graph modules then you can run:

#To get the items
Get-MgDirectoryDeletedItem

#To remove the items
Remove-MgDirectoryDeletedItem -DirectoryObjectId [objectGUID] -confirm:$false

the Remove-MgDirectoryDeletedItem accepts only a string, not an array, for the parameter DirectoryObjectId. So you have to loop. Currently I am not able to query all deleted objects by using the cmdlets.

Without the cmdlets, by directly working with the API it should be simple:

https://docs.microsoft.com/en-us/graph/api/directory-deleteditems-list?view=graph-rest-1.0&tabs=http

In principle we should be able to do something like this, but it is currently not supported:

Get-MgDirectoryDeletedItem -Filter "AdditionalProperties/@odata.type eq '#microsoft.graph.user'"

Funny is that this seems to work:

Get-MgDirectoryDeletedItem -DirectoryObjectId microsoft.graph.user

Even as microsoft.graph.user is a object type and not an object id. But you only get 100 items returned. If I specify the parameter -All I ran into an exception.

So not nice, but should do what you want:

function remove-mgDeletedUsers {
    Get-MgDirectoryDeletedItem -DirectoryObjectId microsoft.graph.user | %{
        Remove-MgDirectoryDeletedItem -DirectoryObjectId $_.AdditionalProperties.value.Id -Confirm:$false
    }
    If (Get-MgDirectoryDeletedItem -DirectoryObjectId microsoft.graph.user){
        remove-mgDeletedUsers
    }
}

This function will query the deleted items for user accounts, and removes them from the recycle.bin. As the query Get-MgDirectoryDeletedItem -DirectoryObjectId microsoft.graph.user only returns max. 100 objects and the switch -All causes a exception, we continue to call it until no objects are found anymore.

Related