Change UPN and email domain for all users (Office365 & AD)

If you’ve got an Office365 setup, with Azure AD Sync there may come a time where you need to change the primary domain name of all you users. Corporate re-branding, merger, etc.

This powershell script will change the on-prem-AD and Office365 UPN suffix, change the primary email address (Inc Skype for Business), while retaining the old address as an alias.

Just fill in $oldSuffix, $newSuffix and $ou!

Connect-MSOLService
Import-Module ActiveDirectory

$oldSuffix = "olddomain.com"
$newSuffix = "newdomain.com"
$ou = "OU=StaffOU,DC=yourCompany,DC=local"

Get-ADUser -SearchBase $ou -filter * -Properties proxyAddresses | ForEach-Object {
  $oldUpn = $_.UserPrincipalName
  $newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)
  $_ | Set-ADUser -UserPrincipalName $newUpn -EmailAddress $newUpn
  $_ | Set-ADUser -Remove @{ProxyAddresses="SMTP:" + $oldUpn}
  $_ | Set-ADUser -Remove @{ProxyAddresses="SIP:" + $oldUpn}
  $_ | Set-ADUser -Add @{ProxyAddresses="SMTP:" + $newUpn}
  $_ | Set-ADUser -Add @{ProxyAddresses="SIP:" + $newUpn}
  $_ | Set-ADUser -Add @{ProxyAddresses="smtp:" + $oldUpn}
  $_ | Set-ADUser -Add @{ProxyAddresses="sip:" + $oldUpn}
  Set-MsolUserPrincipalName -UserPrincipalName $oldUpn -NewUserPrincipalName $newUpn
}

Leave a Reply

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