Delete all users and groups from azure Active Directory. Using Power shell.

Feb 25, 2020 | Azure, Scripting and programming, Technology | 0 comments

I don’t know why you would want to do this. Maybe your boss is being a pain in the rear and you feel like getting back at the world.  This may not be a good idea.  There’s a good chance this may make you rather unpopular around the office and could seriously impact your employment prospects in the future.  But who am I to judge.  Sometimes there’s a perfectly rational reason why you need to delete every user and group from Azure active directory.  So here goes.  Do it with just four lines of code.  I’m not giving you the command to connect because if you don’t know that, you certainly shouldn’t be doing the next part.

# Delete users. First download a CSV. Then delete them.
Get-AzureADUser -All $true | Export-Csv AllAzureADUsers.csv
Import-CSV AllAzureADUsers.csv | Foreach-Object { Remove-AzureADUser -ObjectId $_.UserPrincipalName }

#delete groups. First download a CSV of the groups then delete them.
Get-AzureADGroup -All $true | Export-Csv AllAzureADGroups.csv
Import-CSV AllAzureADGroups.csv | Foreach-Object { Remove-AzureADGroup -ObjectId $_.ObjectId }

Restore deleted users from Azure active directory

Okay. So you’ve deleted everyone but now you need to restore them again because you’ve decided you value your job after all.
This code restores the users but it restores them with a new UPN. This is really useful as if you’ve re-used that custom domain in another subscription for example, you can’t restore the users that were previously deleted using the same UserPrincipalName. OF course, if that’s not relevant just delete that part from the code.

Import-CSV c:\ps\Azure\AllAzureADUsers.csv | Foreach-Object {
$NewUserPrincipalName = $_.UserPrincipalName.Replace('domain.tld','SubDomain.onmicrosoft.com')
Restore-MsolUser -ObjectId $_.ObjectId -AutoReconcileProxyConflicts -NewUserPrincipalName $NewUserPrincipalName
}

You will notice, I’m re-using the CSV created when deleting the users earlier.

0 Comments

Submit a Comment

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.