Cleaning up unused domains from Exchange users

Article Index


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,,"

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"
$i = $i – 1
Set-Mailbox -Instance $_
#write-output $_.EmailAddresses.count
#Write-output "remaining: " $_.EmailAddresses