Environment: Active Directory with Azure Active Directory Connect and Exchange Online

I had a job recently where I needed to change everyone’s email address to a new domain but I couldn’t accomplish this from Exchange Online as all the users are synchronized with Active Directory on-premises.

I wrote a quick script that addresses this:

<#
PowerShell
Objectives
– query AD with all users with a ‘mail’ attribute
– update the ‘mail’ attribute to the new domain
– set the proxyaddress SMTP matching the mail attribute to lowercase smtp
– set the proxyaddress SMTP to the new domain

Author: Jason Zondag
Date: 2202.08.11
#>
# Set Variables
$newMailDomain = “newdomain.com”
$oldMailDomain = “olddomain.com”

# Make sure we have AD access
Import-Module ActiveDirectory

# Set the SearchBase
$SearchBase = “DC=domain,DC=local”

# Get the required data and loop
$Users = Get-ADUser -Filter “mail -like ‘*'” -SearchBase “$SearchBase” -ResultSetSize $null -properties mail,proxyaddresses,samaccountname,givenname,sn
ForEach ($User in $Users) {
# split the mail attribute to it’s components
$mailName, $mailDomain = $user.mail -split “@”
$updatedMailName = $mailName + “@” + $newMailDomain

# get the user primary SMTP address
$primaryaddress = $user.proxyAddresses -clike ‘SMTP:*’

# split the primary address to get the mail domain
$primaryNAMEwSMTP, $primarySMTP = $primaryaddress -split “@”
$dumpSMTP,$primaryName = $primaryNAMEwSMTP -split “:”

# compare $primarysmtp to $newMailDomain – if it matches do nothing otherwise convert the string SMTP to smtp and add the new primary address

if ($primarySMTP -eq $newMailDomain) {
write-host “$user.mail – Already set” -foregroundcolor Green
} else {
write-host “$user.mail needs to be updated” -foregroundcolor Red
$oldAddress = $user.mail
$newAddress = $primaryName + “@” + $newMailDomain
Set-Aduser $User -remove @{proxyaddresses=”SMTP:$oldAddress”}
Set-Aduser $User -add @{proxyaddresses=”SMTP:$newAddress”}
Set-Aduser $User -add @{proxyaddresses=”smtp:$oldAddress”}
Set-AdUser $User -replace @{mail=”$newAddress”}
write-host “$newAddress is now the the Mail and PrimarySMTP address” -foregroundcolor Green
write-host “$oldaddress has been set as an alias” -foregroundcolor Yellow
}

}

Note – you must run this script with elevated privileges.

I would also recommend that you add the command to stop AAD Sync during the course of running the script.