I needed to update userprinicipalname attribute for users on Active Directory for a specific OU using Powershell.
In order to do that you need to (details below):
- Add alternative UPN suffixes on the Domain
- Execute PowerShell script that retrieves the users and update their UPN
Add Alternative UPN Suffix
- Log on to Domain Controller
- Administrative Tools > Domains and Trusts
- Right on the domain > Properties
- UPN, Add your entries.
Update UPN using Powershell
Luckily, Hesham Amin has written Working with Active Directory using PowerShell. I used that and modified that code a bit to fit my needs. Remember to change the OU LDAP path and the suffix.
#Set-ExecutionPolicy RemoteSigned
$rootOU=[ADSI]LDAP://ou=childOU,ou=parentOU,dc=demo,dc=com
$suffix="customdomain.com"
$searcher= New-Object System.DirectoryServices.DirectorySearcher
$searcher.searchroot=$rootOU
$searcher.Filter = "objectclass=user"
$searcher.SearchScope=[System.DirectoryServices.SearchScope]::Subtree
$res=$searcher.FindAll()
foreach($u in $res)
{
$user = $u.GetDirectoryEntry()
$name=$user.sAMAccountname
$user.userPrincipalName="$name@$suffix"
$user.SetInfo()
$user.psbase.Dispose()
}
$rootOU.psbase.Dispose()
$res.Dispose()
$searcher.Dispose()
Thanks Hesham
Think Powershell!!
Mohamed Yehia