Azure AD – PowerShell Script to Change UPN of All Users in a Group

Posted on Updated on

Imagine that if users in a domain have a UPN suffix which is not a public domain, such as @company.local instead of  When those users synchronize into Azure AD for EMS, Intune, O365, etc., then the users’ UPNs will be instead of a friendly UPN for logging into portals or for enrolling devices.

This is an instance that recently occurred for a customer.  There are plenty of PowerShell examples around for how to change the UPN of users in Azure AD.  However, this customer wanted the ability to only change the users that were part of a specific AD group, rather than the entire organization.

The following PowerShell script can do exactly just that.  But please use extreme caution and thoroughly test the script first as well as the impact to those users and the Microsoft cloud technologies which they use.  There are high risks and many possible negative side effects.  Use this script at your own risk.

# This script will change the UPN for the user members of an AD group
$AdGrp = "EMS_Users"
$oldSuffix = ""
$newSuffix = ""

# Get the AD Group in Azure
$AzAdGrp = Get-MsolGroup -All | Where-Object { $_.DisplayName -eq $AdGrp }
$AzAdGrp_members = Get-MsolGroupMember -All -GroupObjectId $AzAdGrp.ObjectId
write-host "Total members of group: " $AzAdGrp_members.Count

# Create array of users to change
# Example command to test only a portion of the users in the group:
$users = Get-MsolGroupMember -All -GroupObjectId $AzAdGrp.ObjectId | Get-MsolUser | Where-Object { $_.UserPrincipalName -like "*john.doe*"}
# Command to run for all users in the group:
# $users = Get-MsolGroupMember -All -GroupObjectId $AzAdGrp.ObjectId | Get-MsolUser

# Change UPN of users
$users | ForEach-Object {
    $newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)
    Set-MsolUserPrincipalName -NewUserPrincipalName $newUpn -UserPrincipalName $_.UserPrincipalName
    Write-host "New UPN assigned: " $newUpn


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s