Your company's ad could live here and reach over 50,000 people a month!

Share This Post

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

Imagine that if users in a domain have a UPN suffix which is not a public domain, such as @company.local instead of @company.com.  When those users synchronize into Azure AD for EMS, Intune, O365, etc., then the users’ UPNs will be @company.onmicrosoft.com instead of a friendly @company.com 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.


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

# 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
}

Filed under: Uncategorized

Share This Post

Leave a Reply