Removing a domain from an Office 365 tenant

It’s never easy to remove a domain from an Office 365 tenant. Microsoft has done very little to simplify this process over the last few years, so I’ve put together some notes on how to remove a domain as efficiently as possible.

First, be sure to convert a tenant to cloud-only at least 3 days before domain removal is required. This is done by doing two things: 1) disabling AADConnect:

Set-ADSyncScheduler -SyncCycleEnabled $false

Then 2) running the below command against the tenant:

Connect-MsolService

Set-MsolDirSyncEnabled -EnableDirSync $false

Typically a tenant will convert to cloud-only within about 24 hours, but Microsoft recommends waiting 72 hours for this process to complete.

When it’s time to remove the domain, you’ll want to create some scripting to change the UPNs of all of your user objects. The command should look something like this:

set-msoluserprincipalname -userprincipalname [email protected] -newuserprincipalname [email protected]

Run that command against all user objects in the tenant.

Now, you’ll need to remove references to the old domain in the mail and proxyaddresses attributes. This can be done by running the following script, found here:

# Get all mailboxes
$Mailboxes = Get-Mailbox -ResultSize Unlimited

# Loop through each mailbox
foreach ($Mailbox in $Mailboxes) {

    # Change @contoso.com to the domain that you want to remove
    $Mailbox.EmailAddresses | Where-Object { ($_ -clike "smtp*") -and ($_ -like "*domain-being-removed.com") } | 

    # Perform operation on each item
    ForEach-Object {

        Set-Mailbox $Mailbox.DistinguishedName -EmailAddresses @{remove = $_ }

        # Write output
        Write-Host "Removing $_ from $Mailbox Mailbox" -ForegroundColor Green
    }
}

In some cases, the above script doesn’t remove everything. If this is the case, you’ll need to export all users from the 365 admin center, then format the output to reveal proxyaddresses being used. From there, you can manually create a script to remove the attributes using the below script as an example:

Set-Mailbox [email protected] -EmailAddresses @{remove="[email protected]"}

You’ll now also need to remove references from group objects in the tenant. You can run the following script to do so, which was found here:

$Groups = Get-DistributionGroup -Resultsize unlimited | where {$_.EmailAddresses -like "*domain-being-removed.com"}

foreach($Group in $groups){  
    
    $temp = $Group.Name
    $temp2 = ((Get-DistributionGroup $temp).EmailAddresses -like "*domain-being-removed.com") -replace "\w*\:" #Using domain name to find the full address

    Set-DistributionGroup $temp -EmailAddresses @{remove=$temp2}
}

Once the above steps are complete, you can use the Office 365 Admin Center to remove the domain. This is found in Settings -> Domains.