Cleaning up unused domains from Exchange users

One of the challenges I had recently when migrating users from Exchange 2007 to Exchange Online (who had been migrated over from Lotus Notes before that) was that they had loads (and loads!) of proxyAddress entries. Every domain the company we integrated had ever owned was stuck onto those mailboxes - but we'd decided to only use a handful in Exchange Online.

When migrating the mailbox from on premise to Exchange Online, the migration failed with the message that the domains on the mailbox were not part of the list of Accepted Domains configured for Exchange Online. Obvously, we could do 2 things: Add all the domains to the Accepted Domains - or clean up the mailboxes. While it did seem like a daunting task, I opted for the latter.


 

In retrospect, it didn't turn out to be much work: I just wrote a Powershell script that does it for me. If you want to use it, just copy/paste the script below to a text file on your Exchange server, adjust the domain names and the mailbox database in which you want to search for mailboxes, save it with a PS1 extension and run it (NB: it will NOT run on Exchange 2013 without some tweaking as I needed it for Exchange 2007)

$MSOnline = "domain1,com,domain2.net,domain3.org"

Get-MailboxDatabase -Identity "<YOUR MAILBOX DB>" | Get-Mailbox | foreach {

#write-output $_.EmailAddresses.count
for ($i=0;$i -lt $_.EmailAddresses.Count; $i++)
{
$address = $_.EmailAddresses[$i]
$domain = $address.AddressString.toString().Split("@")[1]

if (!$MSOnline.Contains($domain) -AND $address.PrefixString -eq "SMTP" ) {
write-host "removing $address"
$_.EmailAddresses.RemoveAt($i)
$i = $i – 1
}
}
Set-Mailbox -Instance $_
#write-output $_.EmailAddresses.count
#Write-output "remaining: " $_.EmailAddresses
}