Bulk changing Active Directory UPNs from PowerShell

As part of my current Office 365 project, I needed to prepare an on-premises Active Directory for synchronisation with Azure AD. This was a test environment that had been created by taking a copy of the production directory, so I had thousands of users – but all with incorrect user principal names (UPNs) that needed to be changed to a new value @test.domainname.tld.

I added the new UPN to the forest in Active Directory Domains and Trusts, then ran the following PowerShell for each OU that contained users I was going to synchronise with Azure AD (discovered via David O’Brien):

Get-ADUser -Filter * -SearchBase 'OU=Employees,OU=Users,OU=CompanyName,DC=DomainName,DC=tld' -Properties userPrincipalName | foreach { Set-ADUser $_ -UserPrincipalName "$($_.samaccountname)@test.domainname.tld"}

The command failed when I ran it on the domain controller (as did the script I originally tried) but when I used PowerShell on another server that was a member of the domain (my Azure AD sync server), it worked. This forum post suggests that it can run locally if you use the -server parameter but I haven’t tried that.  Just be sure to run Import-Module ActiveDirectory first, or else the *-ADUser commands won’t be available.

Leave a Reply