Removing SMTP Addresses for non-existent domains within Office 365

The below PowerShell script will assist in removing SMTP addresses for on-premise users that are non-existent within Office 365.

[Background]

When migrating users to Office 365 from MS Exchange on-premise environment, the migration will fail if the user being migrated has SMTP addresses for domains that are non-existent within Office 365. This is especially the case for X400 or X500 addresses.

[How To]

To run the script, save the below code snippet as a PowerShell script and run it from within Exchange Management Shell passing it the identity of the user being migrated.

You will need to modify the code to add your domains that DO exist in Office 365

For example:

.\RemoveSMTPAddresses.ps1 john.doe

[Code]

param(
  [string] $identity
)

$domains = @("domain1","domain2","domain3","domain4")
function CheckDomain ([string] $addressCheck)
{
  for ($j=0; $j -lt $domains.Count; $j++)
  {
     $domain = $domains[$j]
     if ($address.SmtpAddress -like "*$domain")
	 {
	    return $true
	 }
  }
  return $false
}

$Mailboxes = Get-Mailbox -identity $identity

$Mailboxes | foreach{
    for ($i=0;$i -lt $_.EmailAddresses.Count; $i++)
    {
        
        $address = $_.EmailAddresses[$i]
        if ((CheckDomain "$address.SmtpAddress") -eq $false)
        {
            Write-host($address.AddressString.ToString())
            $_.EmailAddresses.RemoveAt($i)
            $i--
        }
    }
    Set-Mailbox -Identity $_.Identity -EmailAddresses $_.EmailAddresses
}