Wasn’t perfect but did what needed. Changed all user names from swhiting to steven.whiting. Doesn’t change the login so can still use the old swhiting for logging in, was just easier. Despite the UPN changing, it oddly doesn’t update the Entra ID when it syncs to Azure. Still looking into that, but this ended up being for the best. Cause of the way our domain was originally setup you have to sign in as swhiting@stevenwhiting.co.uk so having to do the full steven.whiting@ would be annoying.
<#!
.SYNOPSIS
Update UPN and Primary SMTP Address for specific users identified by sAMAccountName (hybrid AD + Entra ID).
.DESCRIPTION
- Targets ONLY the sAMAccountNames you specify (hard list below).
- For each user, builds the new identity as firstname.surname@stevenwhiting.co.uk
based on their AD GivenName + Surname (lowercased; non-alphanumerics removed).
- Updates on-prem AD so hybrid sync flows changes to Entra ID/Exchange Online:
* userPrincipalName (UPN)
* mail (primary SMTP)
* proxyAddresses (sets new Primary as 'SMTP:' and preserves old sAMAccountName as alias 'smtp:')
* mailNickname (left part)
- Writes a dated CSV log for auditing and rollback.
- Includes rollback mode.
.PARAMETER AlsoSetExchangeOnline
Attempt to set primary SMTP in Exchange Online as well (OFF by default; hybrid sync usually overwrites EXO-only changes).
.PARAMETER RollbackPath
Path to a previous CSV log from this script to revert changes.
.NOTES
Author: Steven Whiting – Using Chat GPT so may not be perfect but it worked and did what I needed it to do. Probably better ways to do it. With this script you also have to manually edit the users you want changed. I quite liked that for safety.
Date: 2025-09-23
This script uses CmdletBinding(SupportsShouldProcess=$true).
Use -WhatIf on the script to preview, and -Confirm to be prompted.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[switch]$AlsoSetExchangeOnline,
[string]$RollbackPath
)
Import-Module ActiveDirectory -ErrorAction Stop
# ---------- Helpers ----------
function Write-Info($msg) { Write-Host "[INFO ] $msg" -ForegroundColor Cyan }
function Write-Warn($msg) { Write-Warning $msg }
function Write-Err ($msg) { Write-Host "[ERROR] $msg" -ForegroundColor Red }
function Get-PrimarySmtpFromProxies([string[]]$Proxies) {
if (-not $Proxies) { return $null }
$p = $Proxies | Where-Object { $_ -cmatch '^SMTP:' } | Select-Object -First 1
if ($p) { return ($p -replace '^SMTP:','') }
return $null
}
function Build-NewAddressParts([string]$GivenName,[string]$Surname,[string]$Domain) {
if ([string]::IsNullOrWhiteSpace($GivenName) -or [string]::IsNullOrWhiteSpace($Surname)) {
throw "GivenName/Surname missing; cannot build firstname.surname."
}
$fn = ($GivenName -replace "[^A-Za-z0-9]", "").ToLower()
$sn = ($Surname -replace "[^A-Za-z0-9]", "").ToLower()
$local = ("{0}.{1}" -f $fn, $sn)
return @{ Local=$local; Upn=("{0}@{1}" -f $local,$Domain); Primary=("{0}@{1}" -f $local,$Domain); Nick=$local }
}
function Ensure-UniqueUpn([string]$CandidateUpn,[string]$DomainNC,[string]$UserDN) {
$exists = Get-ADUser -Filter ("userPrincipalName -eq '{0}'" -f $CandidateUpn) -SearchBase $DomainNC -ErrorAction SilentlyContinue
if (-not $exists -or ($exists.DistinguishedName -eq $UserDN)) { return $CandidateUpn }
$prefix,$suffix = $CandidateUpn.Split('@')
for ($i=1; $i -lt 1000; $i++) {
$try = "{0}{1}@{2}" -f $prefix,$i,$suffix
$exists = Get-ADUser -Filter ("userPrincipalName -eq '{0}'" -f $try) -SearchBase $DomainNC -ErrorAction SilentlyContinue
if (-not $exists -or ($exists.DistinguishedName -eq $UserDN)) { return $try }
}
throw "Unable to find a unique UPN after 999 attempts for $CandidateUpn"
}
function Set-UserMailAttributes {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Microsoft.ActiveDirectory.Management.ADUser]$User,
[string]$NewUpn,
[string]$NewPrimarySmtp,
[string]$NewMailNick,
[string]$DomainSuffix
)
$dn = $User.DistinguishedName
$currentProxies = @($User.proxyAddresses)
# Demote any existing primary entries to alias form (lowercase)
$proxiesNoPrimary = @()
foreach ($p in $currentProxies) { $proxiesNoPrimary += ($p -replace '^SMTP:','smtp:') }
# Add old sAMAccountName as alias
$newAliasAdded = "$($User.SamAccountName)@$DomainSuffix"
if ($proxiesNoPrimary -notcontains ("smtp:$newAliasAdded")) {
Write-Info "Adding old sAMAccountName as alias: smtp:$newAliasAdded"
$proxiesNoPrimary += "smtp:$newAliasAdded"
}
# Remove duplicates and any lingering entry that collides with new primary
$proxiesNoPrimary = $proxiesNoPrimary | Sort-Object -Unique | Where-Object { $_ -ne ("smtp:$NewPrimarySmtp") -and $_ -ne ("SMTP:$NewPrimarySmtp") }
# Final list: new primary first, then aliases
$finalProxies = @("SMTP:$NewPrimarySmtp") + $proxiesNoPrimary
# Ensure array of strings
if ($finalProxies -isnot [array]) { $finalProxies = @($finalProxies) }
$finalProxies = $finalProxies | ForEach-Object { [string]$_ }
$replace = @{
proxyAddresses = $finalProxies
mail = $NewPrimarySmtp
mailNickname = $NewMailNick
}
if ($PSCmdlet.ShouldProcess($User.SamAccountName, "Set mail attributes and UPN")) {
Set-ADUser -Identity $dn -UserPrincipalName $NewUpn -Replace $replace -ErrorAction Stop
}
return @{
NewProxies = $finalProxies
NewAliasAdded = "smtp:$newAliasAdded"
}
}
# ---------- Config ----------
$DomainSuffix = 'stevenwhiting.co.uk'
$DomainNC = 'DC=stevenwhiting,DC=co,DC=uk'
$SearchBaseDN = 'OU=IT,OU=formation,OU=.Users,OU=Steven Whiting,DC=stevenwhiting,DC=co,DC=uk'
$SamAccountNames = @('jwhiting','ldave','swhiting')
# ---------- Resolve targets ----------
$ResolvedUsers = @()
foreach ($sam in $SamAccountNames) {
$found = Get-ADUser -Filter "SamAccountName -eq '$sam'" -SearchBase $SearchBaseDN -Properties GivenName,Surname,mail,mailNickname,proxyAddresses,DistinguishedName,SamAccountName,userPrincipalName
if (-not $found) { Write-Err "User not found in OU scope: $sam"; continue }
if ($found.Count -gt 1) { Write-Err "Multiple matches for sAMAccountName $sam in the scope. Aborting for safety."; exit 1 }
$ResolvedUsers += $found
}
if ($ResolvedUsers.Count -ne $SamAccountNames.Count) {
Write-Err "Expected to resolve $($SamAccountNames.Count) users, but resolved $($ResolvedUsers.Count). Aborting."
return
}
# Confirmation
Write-Host "The following users will be updated:" -ForegroundColor Yellow
$ResolvedUsers | Select-Object SamAccountName, UserPrincipalName, GivenName, Surname, DistinguishedName | Format-Table -AutoSize
$ans = Read-Host "Type YES to proceed (anything else aborts)"
if ($ans -ne 'YES') { Write-Host 'Aborted by operator.'; return }
# ---------- Processing ----------
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$LogPath = Join-Path -Path (Get-Location) -ChildPath ("UPN_SMTP_Change_Log_{0}.csv" -f $timestamp)
$logRows = @()
foreach ($user in $ResolvedUsers) {
try {
$parts = Build-NewAddressParts -GivenName $user.GivenName -Surname $user.Surname -Domain $DomainSuffix
$targetUpn = Ensure-UniqueUpn -CandidateUpn $parts.Upn -DomainNC $DomainNC -UserDN $user.DistinguishedName
$oldPrimarySmtp = Get-PrimarySmtpFromProxies $user.proxyAddresses
if (-not $oldPrimarySmtp -and $user.mail) { $oldPrimarySmtp = $user.mail }
# Skip if already changed
if ($user.UserPrincipalName -eq $targetUpn -and $oldPrimarySmtp -eq $parts.Primary) {
Write-Host "$($user.SamAccountName) is already updated. Skipping..." -ForegroundColor Yellow
$logRows += [pscustomobject]@{
When = (Get-Date)
DN = $user.DistinguishedName
SamAccountName = $user.SamAccountName
DisplayName = $user.Name
OldUPN = $user.UserPrincipalName
NewUPN = $targetUpn
OldPrimarySMTP = $oldPrimarySmtp
NewPrimarySMTP = $parts.Primary
FinalProxyAddresses = ($user.proxyAddresses -join ';')
NewAliasAdded = "$($user.SamAccountName)@$DomainSuffix"
Result = "Already changed"
}
continue
}
Write-Info ("Processing {0}:" -f $user.SamAccountName)
$result = Set-UserMailAttributes -User $user -NewUpn $targetUpn -NewPrimarySmtp $parts.Primary -NewMailNick $parts.Nick -DomainSuffix $DomainSuffix
Write-Host " Final ProxyAddresses:"
foreach ($proxy in $result.NewProxies) {
if ($proxy -cmatch '^SMTP:') { Write-Host " $proxy (Primary)" -ForegroundColor Green }
else { Write-Host " $proxy (Alias)" -ForegroundColor DarkGray }
}
Write-Host " New alias added: $($result.NewAliasAdded)" -ForegroundColor Magenta
$logRows += [pscustomobject]@{
When = (Get-Date)
DN = $user.DistinguishedName
SamAccountName = $user.SamAccountName
DisplayName = $user.Name
OldUPN = $user.UserPrincipalName
NewUPN = $targetUpn
OldPrimarySMTP = $oldPrimarySmtp
NewPrimarySMTP = $parts.Primary
FinalProxyAddresses = ($result.NewProxies -join ';')
NewAliasAdded = $result.NewAliasAdded
Result = "Success"
}
}
catch {
Write-Err $_.Exception.Message
}
}
$logRows | Export-Csv -NoTypeInformation -Path $LogPath
Write-Info "Log written to: $LogPath"