Clean up references to your custom domain name from an Azure AD test tenant

Today I needed to move my custom domain name from an old (and messy) AAD test tenant to a (sparkling) new one. Problem is, you can’t simply delete the old custom name, since your user’s UPNs and Email addresses are using it (AAD actually presents a nice screen, showing all the dependencies, but I am writing this post after I’ve done everything, sorry). Changing them manually is out of question – too long, and some fields like SMTP Proxy can’t be changed at all. Fortunately, there is PowerShell to the rescue!

Here is the script that I wrote. Please note, that some parts of this script were “optimized” after I had completed everything, and your setup may be different, but you’ll get the point. The script leverages the Azure AD and Exchange Online PowerShell modules, which you might need to install and connect to (see the commented out lines). The names of domains and users are replaced with #####.

# Install-Module AzureAD;
# Import-Module AzureAD;
# Install-Module ExchangeOnlineManagement; 
# Import-Module ExchangeOnlineManagement;

# Connect-AzureAD;
# Connect-ExchangeOnline -UserPrincipalName #####;

$DNcustom = "";
$DNmsol = "";

$AADusers = Get-AzureADUser;

foreach ($AADuser in $AADusers) { 
    Set-Mailbox $AADuser.UserPrincipalName -Emailaddresses @{remove=${"smtp:" + $AADuser.MailNickName + "@" + $DNcustom}};
    Set-AzureADUser -ObjectId $AADuser.ObjectId -UserPrincipalName ${$AADuser.MailNickName + "@" + $DNmsol};

Generally, this is it – the script walks over all the users you have, removes the email and SMTP proxy bound to the old domain name (my users still retained their emails), and changes the UPN to the old It may throw some errors for the service accounts you have (that have no emails etc) – but worked fine for me.

In less that a minute I was able to free up my tenant from the mentions on the old domain name and delete it. Now I can associate this custom domain name with a new tenant. Hope it could help you someday!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

Up ↑

%d bloggers like this: