Using PowerShell to change the User Principal Name (UPN) for a user in Active Directory!

Frequent Contributor

 

Dear Windows Active Directory friends,

 

I am absolutely aware that there are probably already a lot of articles on this topic. Nevertheless, I would like to show you my steps how I did this in a small infrastructure.
But why would I want to change the User Principal Name (UPN)? Let's say you want to synchronize the
local Active Directory with the Azure Active Directory and you use in the local domain the DNS suffix e.g. tomrocks.local, then the accounts in Azure are created with the default DNS suffix e.g.
yourcompany.onmicrosoft.com.

 

In my case, I added a custom domain in Azure: tomrocks.ch. In order to create the accounts correctly
in Azure, the first step is to adjust the UPN of the users in the local Active Directory. I use the PowerShell ISE for this, but of course you may also work with another editor.

 

Please start with the following steps to begin the "journey" (the Hashtags are comments):

#The first two lines have nothing to do with the configuration but make some space at the bottom of the ISE.
Set-Location C:\
Clear-Host

 

#Get a list of the UPN suffixes
Get-ADForest | Format-List UPNSuffixes

 

#Let’s add the UPN suffix
Get-ADForest | Set-ADForest -UPNSuffixes @{add="tomrocks.ch"}

 

#Get a list of the UPN suffixes
Get-ADForest | Format-List UPNSuffixes

 

#List of all the AD Users in the organization
Get-ADUser -Filter * | Sort-Object Name | Format-Table Name, UserPrincipalName

 

#Change the UPN for all the AD users in the organization
$LocalUsers = Get-ADUser -Filter {UserPrincipalName -like '*tomrocks.local'} -Properties UserPrincipalName -ResultSetSize $null
$LocalUsers | foreach {$newUpn = $_.UserPrincipalName.Replace("tomrocks.local","tomrocks.ch"); $_ | Set-ADUser -UserPrincipalName $newUpn}

 

#Confirm that the UPN is changed
Get-ADUser -Filter * | Sort-Object Name | Format-Table Name, UserPrincipalName

 

I know this is nothing spectacular at all, but I wanted to share my findings and experiences with you.

Thank you for your attention. Kind regards, Tom Wechsler

 

P.S. All scripts (#PowerShell, Azure CLI, #Terraform, #ARM) that I use can be found on github! https://github.com/tomwechsler

2 Replies
Thanks for sharing. I am sure that you know this more than I do.
It's all about communicating and sharing the knowledge and what we find and learn.
Thanks for sharing.
It's always a pleasure! Regards, Tom Wechsler