Change UPN (based on Primary Email) based on SMTP: in proxy addresses

So there are numerous scripts out there for setting the UPN of a user to match the Windows Email Address.. you can even do that in a single command (Powershell).. but would it not be better to actually read the primary e-mail address from the ProxyAddresses? .. so the following script will help you with that:

<<Copy the following into a .ps1 file and run it directly from Powershell (make sure you have AD PowerShell CMD’lets available).. it will by default NOT make any changes, but it will create an output file you can validate. Once you are ready to execute run the script with /tm:no as an option.. >>

 

Param($Param2)
$bolTestMigration=$true
If ($Param2 -eq "/tm:no") {
Write-Host "Production Migration - Making Changes!"
$bolTestMigration=$false}
ELSE {$bolTestMigration=$true}
 $ScriptLocation="C:Scripts"
$DateStamp = get-date -uformat "%Y-%m-%d-%H-%M-%S"
$Logfile = $Logfile = ($ScriptLocation + "UPNSET-" + $DateStamp + ".log")
 Function LogWrite
{
Param ([string]$logstring)
Add-content $Logfile -value $logstring
Write-Host $logstring
}
 Write-Host " Loading Active Directory cmdlets"
Import-Module ActiveDirectory
 #For each object in our environment, we are going to look up the proxyAddresses, get the address that starts with SMTP: and use that as the UPN
$CollObjects=Get-ADObject -LDAPFilter "(&(legacyExchangeDN=*)(objectClass=user))" -Properties ProxyAddresses,distinguishedName,userPrincipalName
Write-Host $CollObjects.count
foreach ($object in $CollObjects){
$Addresses = ""
$DN=""
$UserPrincipalName=""
#Write-Host "Found: " $object.DisplayName
$Addresses = $object.proxyAddresses
$ProxyArray=""
$DN=$object.distinguishedName
ForEach ($Address In $Addresses)
{
$ProxyArray=($ProxyArray + "," + $Address)
If ($Address -cmatch "SMTP:")
{
$PrimarySMTP = $Address
$UserPrincipalName=$Address -replace ("SMTP:","")
#Found the object validating UserPrincipalName
If ($object.userPrincipalName -notmatch $UserPrincipalName) {
If ($bolTestMigration -eq $false) {
Write-Host "." -ForegroundColor Blue
LogWrite ($DN + ";" + $object.userPrincipalName + ";NEW:" + $UserPrincipalName)
Set-ADObject -Identity $DN -Replace @{userPrincipalName = $UserPrincipalName}
}
If ($bolTestMigration -eq $true) {
Write-Host "." -ForegroundColor Blue
LogWrite ($DN + ";" + $object.userPrincipalName + ";NEW:" + $UserPrincipalName)
Write-Host "was:" $object.userPrincipalName
Write-Host "setting:" $UserPrincipalName
Set-ADObject -Identity $DN -WhatIf -Replace @{userPrincipalName = $UserPrincipalName}
}
 }
ELSE {
Write-Host "." -ForegroundColor Green -NoNewline
}
}
}
}
Tagged