How to change UPN for all users in AD using PowerShell

In this article, I will show you how to change UPN for all users in AD using PowerShell. This is useful after adding a new domain to Office 365. The user’s principal name should match the email domain. First, you will need to add the domain to AD. You can check my other posts on How to add a new domain to Office 365 and How to add a new email domain (UPN suffix) to Active Directory.

First, we need to login to the domain controller or install the Active Directory module on your workstation.

On the domain controller open PowerShell as administrator.

You can change the UPN for all users in the domain or filter by OU, or any attribute like the department.

Change UPN for All users in OU

  • To see the current UPN for all users in the OU run the following command:

Get-ADUser -Filter * -SearchBase “OU=Test,DC=yourdomain,DC=com” | Format-Table Name, UserPrincipalName

  • To change the UPN from the old domain to the new domain in the OU run the following commands:

$LocalUsers = Get-ADUser -Filter {UserPrincipalName -like ‘*olddomain.com’} -SearchBase “OU=Test,DC=yourdomain,DC=com” -Properties userPrincipalName -ResultSetSize $null

Replace the highlighted areas below with your internal domain name and OU.

$LocalUsers | foreach {$newUpn = $_.UserPrincipalName.Replace(“olddomain.com”,”newdoamin.com”); $_ | Set-ADUser -UserPrincipalName $newUpn}

Replace with your old and new domain names:

That’s it! After running these two commands, the UPN for all users has changed. To verify the change, you can run the search command again. Now the results should have the new domain.

Change UPN for All users by Department

  • To filter by the department attribute you can use the following command:

Get-ADUser -Filter{department -eq “IT”} | Format-Table Name, UserPrincipalName

  • The command will return all users in the IT department. To change all users in this department the following two commands:

$LocalUsers = Get-ADUser -Filter {UserPrincipalName -like ‘*olddomain.com’ -and department -eq “IT”} -Properties userPrincipalName -ResultSetSize $null

Replace with your internasal domain name and the required department.

$LocalUsers | foreach {$newUpn = $_.UserPrincipalName.Replace(“olddomain.com”,”newdoamin.com”); $_ | Set-ADUser -UserPrincipalName $newUpn}

The second command is the same as before. Again, you would need to replace it with the correct domain names.

Again, after running the two commands we changed the UPN for all users in the department.

One comment

Comments are closed.