Wednesday, March 7, 2007

Script: Globally Replace Email Domain

Have you ever had to globally replace one email domain with another? Maybe you are in the middle of a merger or possibly made a typo in a recipient policy. Searching for and updating idividual email accounts can be tedious.

I couple of weeks ago a friend had a need for a script to identify accounts with an @domainA.com email address and replace it with an @domainB.com address. Below is the script I created to accomplish such a task.

--Nick



## Please set variables as desired below ##
$OldDomain = "@olddomain.com" #Domain address to remove
$NewDomain = "@newdomain.com" #Domain address to add

## Start of script

#Query AD for mailboxes to alter
Get-Mailbox -ResultSize:Unlimited -Filter:"EmailAddresses -like '*$OldDomain*'" | foreach {

#Store Identity of Mailbox
$MailboxID = $_.Identity

#Identify the email addresses to change
$AddressesToChange = $_.EmailAddresses | where { $_.ProxyAddressString -like "*$OldDomain*" }

#Loop through results in case a user has multiple addresses to change
$AddressesToChange | foreach {

#Get email address
$OldAddress = $_.ProxyAddressString

#Remove domain portion of email address
$Username = $_.ProxyAddressString.Split("@")[0]

#Set new email address (format: 'smtp:username@newdomain')
$NewEmailAddress = $Username + $NewDomain

#Check if it is a PrimarySMTP Address
$IsPrimarySMTPAddress = $False
if ($_.IsPrimaryAddress -eq "True" -and $_.PrefixString -eq "smtp")
{
$IsPrimarySMTPAddress = $True
}

#Add new address
Set-Mailbox -Identity:$MailboxID -EmailAddresses:((Get-Mailbox -Identity:$MailboxID).EmailAddresses + "$NewEmailAddress")

#Set new address as primary address if needed
If ($IsPrimarySMTPAddress)
{
#Remove 'smtp:' from start of the string
$PrimarySmtpAddress = $NewEmailAddress.Split(":")[1]
Set-Mailbox -Identity:$MailboxID -PrimarySmtpAddress:$PrimarySmtpAddress -WindowsEmailAddress:$PrimarySmtpAddress
}

#Remove the old address
Set-Mailbox -Identity:$MailboxID -EmailAddresses:((Get-Mailbox -Identity:$MailboxID).EmailAddresses | where { $_.ProxyAddressString -notlike "$OldAddress" })

Write-Host $OldAddress "has been replaced with" $NewEmailAddress
}
}


Disclaimer

Sample scripts are provided AS IS without warranty of any kind. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages.

No comments: