Rewriting the UserPrincipalName (Suffix) in Powershell

Here’s a little script I wrote to assist with our company integration efforts. All it does is rewrite the domain suffix of the UPN to a new domain, it’s grabbing it’s information from a csv called book1 that only contains UPN’s. To create that file you can run the following from a 08r2 or later domain controller:


get-aduser | FT userprincipalname | export-csv "C:usersdododesktopbook1.csv

Here’s the script:


start-transcript c:usersdododesktoptrans.txt
#get the users
$users=get-content "c:usersdododesktopbook1.csv"
#start the loop
foreach ($user in $users) {
#get the ADuser
$aduser=get-aduser $user
#conditional rewrite logic
if ($aduser.userprincipalname -like "*@domain.com"){
$UPN = $aduser.UserPrincipalName.Replace("domain.com","newdomain.com")
Set-ADUser $user -UserPrincipalName $UPN
}
elseif ($aduser.userprincipalname -like "*@sub.domain.com"){
$UPN = $aduser.UserPrincipalName.Replace("@sub.domain.com","@newdomain.com")
Set-ADUser $user -UserPrincipalName $UPN
}
elseif ($aduser.userprincipalname -like "*@asdf.LAN"){
$UPN = $aduser.UserPrincipalName.Replace("@asdf.LAN","@newdomain.com")
Set-ADUser $user -UserPrincipalName $UPN
}
elseif ($aduser.userprincipalname -like "*@lala.asdf.LAN"){
$UPN = $aduser.UserPrincipalName.Replace("@lala.asdf.LAN","@newdomain.com")
Set-ADUser $user -UserPrincipalName $UPN
}
else {
Write-host "nothing to do for this address"
}
}
Stop-transcript




Leave a Reply

Your email address will not be published. Required fields are marked *