I had a requirement to update a bunch a users from the locally made UPN of loginid@bear.local to the new UPN of FirstName.Surname@pokebearswithsticks.com - this is how I did it, however the only weird requirement was I required a list of OU's to exclude that could be expanded.
WARNING: Please do not just run scripts from the internet without checking them and ensuring you know what they are doing, this could break you domain or user logins, this script will write/change attributes to your domain
$targetUPNSuffix = "pokebearswithsticks.com"
# Define an array of excluded OU Distinguished Names
$excludedOUs = @(
"OU=NotforUpdate,DC=bear,DC=local",
"OU=HiddenBears,DC=bear,DC=local"
)
# Get all user accounts in Active Directory excluding the specified OUs
$users = Get-ADUser -Filter * -SearchBase (Get-ADRootDSE).defaultNamingContext -SearchScope Subtree | Where-Object {
$excluded = $false
foreach ($excludedOU in $excludedOUs) {
if ($_.DistinguishedName -like "*$excludedOU*") {
$excluded = $true
break
}
}
-not $excluded
}
# Loop through each user and update their UPN based on first name and last name
foreach ($user in $users) {
# Construct the new UPN based on first name, last name, and the target UPN suffix
$firstName = $user.GivenName
$lastName = $user.Surname
$newUPN = ($firstName + "." + $lastName).ToLower() + "@" + $targetUPNSuffix
# Set the new UPN for the user
Set-ADUser -Identity $user -UserPrincipalName $newUPN
# Output a message to indicate the UPN update
Write-Host "Updated UPN for $($user.SamAccountName) to $newUPN"
}