Removing shared mailboxes
Hello everyone,
I have to remove several shared mailboxes from our tenant and I am going to do this via a PowerShell script. As you may know, every time you try to remove a mailbox using the "remove-mailbox" cmdlet, you will get the following error:
This mailbox cannot be permanently deleted since there is a user associated with this mailbox in Azure Active Directory. You will first need to delete the user in Azure Active Directory. Please refer to documentation for more details.
So you have first to delete the user from Azure, then the mailbox. This is the code I usually run:
$MbxToRemove = Get-Content -Path "C:\Temp\MbxToRemove.txt"
foreach ($mbx in $MbxToRemove){
Remove-MsolUser -UserPrincipalName $mbx -Force
Start-Sleep 15
Remove-MsolUser -UserPrincipalName $mbx -RemoveFromRecycleBin -Force
Start-Sleep 60
Remove-Mailbox -Identity $mbx -PermanentlyDelete -Confirm:$false
}
I need to pause the script for one minute before running the Remove-Mailbox cmdlet otherwise the system will still see the "deleted user". The txt file is a simple list with all the UserPrincipalName of the shared mailboxes.
I was wondering if there is a way to speed up things a bit (=better code). When you have to process 100/150 mailboxes, this takes a certain amount of time.
Many thanks in advance,
Francesco
- That's because you are using the -PermanentlyDelete switch. As the documentation says, this switch is used for removing soft-deleted mailboxes:
This switch works only on mailboxes that have already been deleted, but are still recoverable (known as soft-deleted mailboxes).
Simply do it like this:
Remove-Mailbox shared -Force