Wednesday, May 25, 2011

Powershell script to change UPN suffix of an existing user


One of the things that I really hate about using UPN suffixes in Active Directory is that it doesn't sort the list Alphabetically. So if you've got a server with say 50 UPN suffixes you have to scroll through all of them. So here's a script my colleague wrote to do a quick changeover. (Watch out for wrapped text if you copy and paste this out. Some of the write host commands are too long for blogspot.)

#####################################################################
#
# Script to change UPN of an AD User
#
# Co-authored by Gnawgnu
#
# Last edited 5/25/11
#
####################################################################

Import-Module ActiveDirectory

Function ChangeUPN ($samName2, $upnName2) {
#test for existence
$samDead = get-aduser $samName2
if(!$samDead) {
write-Host "Account not found"
} else {
$fullupn = $samName2 + "@" + $upnName2
write-host ""
write-host "Changing to $fullupn now" -foregroundcolor green
write-host ""
set-ADUser $samName2 -userprincipalname $fullupn
}
}

if ($Args.Count -lt 2) {
write-host ""
write-host "=================== You Failed ===================" -foregroundcolor red
write-host ""
write-host "Enter in user logon name AND and email suffix" -foregroundcolor red
write-host ""
write-host " Example: ChangeUPN.ps1 myusername test.local" -foregroundcolor yellow
write-host " Do NOT include the @ symbol" -foregroundcolor yellow
write-host ""
write-host "Try again" -foregroundcolor red
write-host ""
} else {
$samName = $Args[0]
$upnName = $Args[1]
write-host "Congrats on following directions"
write-host ""
write-host "Changing UPN for user $samName to be $upnName" -foregroundcolor green
write-host ""
write-host "Please allow up to 5 minutes for AD to refresh"

ChangeUPN $samName $upnName

}

No comments: