Active Directory

Script UPN to Primary SMTP Address

During Office 365 migrations I often need to write a script to transform the user accounts UPN’s to match the Primary SMTP address for a uniform username & sign in experience.

I have seen a few scripts out there that try to achieve this but a lot of them fail to read the primary SMTP address from the ProxyAddresses field and instead just write It is vitally important to use the primary SMTP address, especially if you have multiple email domains or names do not always follow the first.last nomenclature.

One caveat to setting the UPN to match the Primary SMTP Address is that the suffix for the SMTP domain is added to Active Directory (under Active Directory Domains & Trusts)

The script is as follows:

# Get all AD users with a primary SMTP address
$UsersWithSMTP = Get-ADUser -properties * -SearchBase "DC=Domain,DC=com" -LdapFilter '(proxyAddresses=*)'
# Loop through all accounts
foreach ($user in $UsersWithSMTP)
# Get the primary SMTP address (UPPER CASE)
$PrimarySMTP = Get-ADUser $user -Properties proxyAddresses | Select -Expand proxyAddresses | Where {$_ -clike "SMTP:*"}
# Remove the protocol specification from the start of the address
$newUPN = $PrimarySMTP.SubString(5)
# Update the user with their new UPN
Set-ADUser $user -UserPrincipalName $newUPN

I recommend running this once on a test OU and then changing the user account creation process moving forward by setting the UPN to the correct (new) format so this script does not have to run daily for new staff.

365 Guy

Microsoft Infrastructure Consultant @ Novosco. Specialising in Office 365, Azure AD & Exchange Server.

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also