Remove SMTP aliases and e-mail addresses from all mailboxes on Exchange 2007 with PowerShell

When migrating your on-premises Exchange organization to Office 365: Exchange Online a common challenge is removing old and unused SMTP aliasses or e-mail addresses.

It’s rather easy to create new SMTP addresses to a mailbox or recipient in Exchange via an e-mail address policy. However it can be a real pain in the ass removing specific e-mail addresses and namespaces on mailboxes. Since it is not allowed to have unaccepted domain SMTP addresses on a mailbox prior migrating to Exchange Online this is a core requirement and activity to be carried out.

Another challenge is the incapability of the version of the Exchange 2007 Management Shell to run this special hash table syntax which is only supported for Exchange 2010 SP1 or higher. Most of the PowerShell scripts I looked for use this particular syntax, making them useless for Exchange 2007.

For this example I used the domainname contoso.com to be removed from all User and Shared Mailboxes within the Exchange organization.

$alias = Get-Mailbox -ResultSize Unlimited | Where {$_.EmailAddresses -like ‘*contoso.com’}
$alias | Select-Object -property SamAccountName,UserPrincipalName,EmailAddresses,PrimarySmtpAddress | Export-Csv “mailboxes_with_contoso.com.csv”

foreach($L in $alias)
{
$x = $L
$y = $x.EmailAddresses | where{$_.AddressString -like ‘*@contoso.com’}
$z = $y.SmtpAddress
$T = $x.UserPrincipalName
Write-host $x.EmailAddresses
Write-host “*****”
if($z){
$x.EmailAddresses -= $z
$x | Set-mailbox
Write-Host “$z is removed”
Write-Host “Check”
Write-host $x.EmailAddresses
}else{
Write-Host “$T does not have a contoso.com SMTP Address.”
}
Write-host “####################################################”
#Return
}

This script will iterate through each mailbox, and look for an address containing the @contoso.com namespace. Any matches are removed. To use this code, just replace contoso.com with the e-mail domain you want to remove. The script also contains some logging for you to digg to if you’re up for it.

In my scenario this was required for removing the unvalidated Office 365 domains prior to migrating mailboxes. When you have succesfully executed the script don’t forget to kick off a Full DirSync to make sure the changes are synced to Windows Azure Active Directory.

Best of luck to you all with carrying out succesfull Office 365 deployments. Before I publish the post, I have thank to my colleague and teammate Dev Chaudhari for working on the scripting!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s