Most companies have domains in their exchange that they aren’t actively using but keep for legacy reasons. One of my customers wanted to clear out an old domain from all objects since they started to get spam on those addresses. So there are to simple solutions:

  1. Remove the domain from AcceptedDomains
  2. Remove the domain from EmailAddressPolicy / All objects

They choose to go down road 2. They have very few EmailAddressPolicies we opted that they clean out the policies them self and I wrote a script to clean out the objects.

Remove all domain entries from proxyaddresses

$DomainToRemove = 'oldcompany.se'
Get-ADObject -ldapFilter "(&(proxyaddresses=smtp:*@$domaintoRemove*)(!(name=SystemMailbox{*))(!(name=CAS_{*))(!(msExchRecipientTypeDetails=16777216))(!(msExchRecipientTypeDetails=536870912))(!(msExchRecipientTypeDetails=8388608)))" -Properties proxyaddresses -PipelineVariable ADObject|ForEach {
 $EmailAddressesToKeep = $ADObject.proxyaddresses|Where-Object {$_ -notlike "smtp:*@$($DomainToRemove)"}
 $EmailAddressesToRemove = $ADObject.proxyaddresses|Where-Object {$_ -like "smtp:*@$($DomainToRemove)"}
 ForEach ($Email in $EmailAddressesToRemove)
 {
 Write-Host "Removing $($Email) from [$($ADObject.ObjectClass)] $($ADObject.DistinguishedName)"
 }
 Switch ($ADObject.ObjectClass)
 {
 'user' {Set-Mailbox -Identity $ADObject.ObjectGuid.toString() -EmailAddresses @{remove=$EmailAddressesToRemove}}
 'group' {Set-DistributionGroup -Identity $ADObject.ObjectGuid.toString() -EmailAddresses @{remove=$EmailAddressesToRemove}}
 'contact' {Set-MailContact -Identity $ADObject.ObjectGuid.toString() -EmailAddresses @{remove=$EmailAddressesToRemove}}
 }
}

Remove all domain entries from Email Address Policies

$DomainToRemove = 'Sub.company1.example'
$EmailPolicies = Get-EmailAddressPolicy|Where-Object {$_.EnabledEmailAddressTemplates -like "*$domaintoRemove*"}
ForEach ($Policy in $EmailPolicies)
{
 $Disabled = $Policy.DisabledEmailAddressTemplates
 $Disabled += $Policy.EnabledEmailAddressTemplates |? {$_.AddressTemplateString -like "*@$($DomainToRemove)"}
 $Enabled = $Policy.EnabledEmailAddressTemplates |? {$_.AddressTemplateString -notlike "*@$($DomainToRemove)"}
 #Write-Host "Writing back $($Policy.Name)"
 Set-EmailAddressPolicy -Identity $Policy -EnabledEmailAddressTemplates:$Enabled -DisabledEmailAddressTemplates:$Disabled
}

As always make sure that you test the scripts out of production / without rights and that you have a current backup :)