Partilhar via


Add User Principal Names in Active Directory via PowerShell

Summary : Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell to add user principal names to users in Active Directory.
Hey, Scripting Guy! We are planning for our Active Directory migration, and as part of that, I am reviewing users. The problem is that I found out that whoever set up our original installation did not assign values for user principal names (UPN). This will cause us a problem as we move to a federated environment. Can you offer an easy way to populate this value?
—CG
Hello CG,
Microsoft Scripting Guy, Ed Wilson, is here. This morning I am sitting on our lanai and checking my scripter@microsoft.com email on my Microsoft Surface RT. I received an email from one of my friends in Hawaii. He was telling me about a Hukilau he went to over the weekend. From his description, it makes me want to grab the Scripting Wife and head out west on the next available flight. The big problem right now, is the weather. I prefer August in Australia to August in Hawaii—it is really hot there.
In Active Directory Users and Computers, the UPN shows up as the user logon name. It displays the UPN in two different fields, as shown in the following image.

To find the actual Active Directory attribute name, I add a bunch of AAAs to the user logon name, and select a domain from the drop-down list. I then go into ADSI edit and look up the value. I see the following:

Searching for existing values
I use the Get-ADUser cmdlet to look for existing values for the UserPrincipalName attribute. To find the value of the UserPrincipalName attribute, I have to specify it for the –Properties parameter. I specify the SearchBase of the organizational unit (OU), and I use the * filter. This is shown here:
Get-ADUser -Filter * -SearchBase 'ou=testou,dc=iammred,dc=net' -Properties userPrincipalName
The command and associated output are represented in the following image.

Setting the UPN value
I use the Get-ADUser cmdlet to retrieve all the users to set. I pipe the resulting user objects to the Foreach-Object cmdlet, and in the script block, I use the Set-ADUser cmdlet. The Set-ADUser cmdlet has a –userPrincipalName parameter that makes it easy to set the UPN.
To create the UPN, I use a hardcoded domain name, and I get the user’s name from the Name attribute. I use parameter substitution and the –f format specifier to concatenate the user principal name. The command is shown here (this...(read more)