Removing a domain from Office 365 – the definite script

If you’ve worked with Office 365 for some time, you’ve almost certainly been in the position of having to remove a domain from an Office 365 tenant. In theory an easy job – remove the domain from users and groups, then remove the domain from the tenant. More often than not, this is not the case.

The problem is often finding all traces of the domain. Users UPN, SMTP- and SIP-addresses should be easy enough to find, as is addresses in groups and various other mailboxes. However, no matter how many times I’ve done it, I often end up with the domain unable to being removed – because of some traces I can’t find.

The official guide and the official KB-article won’t always help, because the domain might be left in some object(s) these articles don’t mention.

I find myself calling Microsoft Support in most of these cases. Last time, the helpful technician at Microsoft used a script to find all traces of the domain – a much more thorough script than any cmdlets in the official guide or KB-article. The script found the objects blocking the removal, and I could remove the domain easily after fixing those objects.

Naturally, I asked the technician if he could be so kind as to send the procedure to me. He did. Coupled with this Microsoft Support procedure, I made a PowerShell script which automatically finds all traces of a given domain in an Office 365 tenant.

#Domain to search for
$Domain = ""

#Global administrator credentials
$UserCredential = Get-Credential `
-Message "Please input Global Administrator credentials."

#Connecting to Office 365 and Exchange Online using provided credentials
Connect-MsolService -Credential $UserCredential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange `
-ConnectionUri `
-Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

#Making a string of all potential objects in Office 365
$All = @(Get-Recipient -Identity "*" -ResultSize Unlimited) + `
@(Get-MsolUser -All) + @(Get-MsolUser -All -ReturnDeletedUsers) + `
@(Get-MsolGroup -All) + @(Get-MsolContact -All)

#Searching string of potential objects for traces of domain
$All | ?{$_.EmailAddresses -match $Domain -or `
$_.EmailAddress -match $Domain `
-or $_.UserPrincipalName -eq $Domain `
-or $_.ProxyAddresses -match $Domain} `
| fl UserPrincipalName,EmailAddresses,EmailAddress,ProxyAddresses

#Disconnecting from Exchange Online
Remove-PSSession $Session

Run the script, and perform appropriate action on the returned objects. Deleting might be easiest, but at times you want to keep the objects for some reason. In those cases, removing the record of the domain on that object would be sufficient.

Finally, we can remove domains without spending hours in support calls!

Leave a Reply

Your email address will not be published. Required fields are marked *