How to update UPN for everyone in a specific OU using PowerShell

If you are running an Office 365 migration for a larger number of users and you would rather not sift through hundreds of user accounts to update their UserPrincipalName Attribute in order to have their username be accurate in Office 365 then have I got the script for you! This script will update UPN for everyone within a specific OU, or all in the directory using PowerShell.

update upn

You will need to do this in order to match the domain entered within Office 365.  Otherwise, all users that will sync in a migration will get set as default “yourdomain”  Then you will need to update them manually in Office 365.  I have another script that you can run that will update UPN within Office 365 via PowerShell.

Update UPN within Active Directory Organizational Unit

Copy the following code into a notepad file and save it as “update-UPN.ps1”.

Import-Module ActiveDirectory
$oldSuffix = "[old domain name]"
$newSuffix = "[new domain name]"
$ou = "[the distinguished name value of your OU]"
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)
$_ | Set-ADUser -UserPrincipalName $newUpn

Then go into your PowerShell window and run the script from where you saved it.  You may need to enable Unsigned scripts to run.