Removing a domain from Office 365

I recently came across a problem removing a domain from a office 365 tenancy. The customer was moving a SMTP domain from one office 365 tenancy to another. Users were sync’d to the source tenancy via AAD Connect. This was disabled to enable us to remove the domain from all objects in the tenancy (we wanted to keep the mailboxes as we were using a 3rd party tool to migrate the data from the source to the target mailbox. This was being done on the tenancyname.onmicrosoft.com address due to not being able to register the domain in the target tenancy until it is removed from the source. When we went to remove the domain we received the error: Unable to remove domain. There are user accounts that are associated with this domain.

We will use domain.com as the SMTP domain in this example.

The steps involved on other domains that had worked previously were as follows:

  • Disable AAD Connect – Set-MSOLDirSyncEnabled –EnableDirSync $False
  • Change UserPrincipalName for all users. Set Users primary SMTP address to the tenancyname.onmicrosoft.com address and remove domain.com
  • Change all Groups primary SMTP address to the tenancyname.onmicrosoft.com address and remove domain.com
  • Change all resource mailbox primary SMTP address to the tenancyname.onmicrosoft.com address and remove domain.com
  • Change any contacts that contain domain.com
  • Return all deleted users (Get-MsolUser -ReturnDeletedUsers -DomainName domain.com | fl UserPrincipalName) and remove

All the above was done via scripts but we still received the same error.

To resolve this we ran the following which checks ALL objects in office 365 and lists any objects that contain reference to the domain in question

$a = get-msoluser -all
$b = get-msoluser -all -returndeletedusers
$c = get-msolgroup -all
$d = get-msolcontact -all
$all = $a+$b+$c+$d
$search = “domain.com”
$all | ?{$_.emailaddresses -match $search -or $_.emailaddress -match $search -or $_.userprincipalname -eq $search -or $_.proxyaddresses -match $search}

We could then change the objects that were returned and then remove the domain from the source tenancy and add to the new target tenancy

About the author