From 2a2d852cd0a06293d75a33c625376f4590b5f8d3 Mon Sep 17 00:00:00 2001 From: poslop Date: Thu, 22 Jan 2026 11:46:52 -0600 Subject: [PATCH] email fix script --- FixDomainEmails/FixDomainEmails.ps1 | 75 +++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 FixDomainEmails/FixDomainEmails.ps1 diff --git a/FixDomainEmails/FixDomainEmails.ps1 b/FixDomainEmails/FixDomainEmails.ps1 new file mode 100644 index 0000000..06e0227 --- /dev/null +++ b/FixDomainEmails/FixDomainEmails.ps1 @@ -0,0 +1,75 @@ + +Import-Module ActiveDirectory + +$EmailDomain = "CHANGE ME.com" + +$UPNDomain = "CHANGE ME.com" + +$SearchBase = "" + +$FixProxyAddresses = $false +$FixUPN = $false +$DryRun = $false + +Write-Host "Loading users..." -ForegroundColor Cyan + +$Query = @{ + LDAPFilter = "(&(objectClass=user)(objectCategory=person))" + Properties = "mail","proxyAddresses","userPrincipalName","sAMAccountName" +} +if ($SearchBase -ne "") { $Query.SearchBase = $SearchBase } + +$Users = Get-ADUser @Query + +Write-Host ("Users found: {0}" -f $Users.Count) -ForegroundColor Yellow + +foreach ($u in $Users) { + + $desiredMail = "$($u.sAMAccountName)@$EmailDomain" + $desiredUPN = "$($u.sAMAccountName)@$UPNDomain" + + $changes = @() + + if ($u.mail -ne $desiredMail) { + $changes += "mail → $desiredMail" + if (-not $DryRun) { + Set-ADUser $u -EmailAddress $desiredMail + } + } + + if ($FixProxyAddresses) { + $newPrimary = "SMTP:$desiredMail" + $existing = @() + + if ($u.proxyAddresses) { $existing = @($u.proxyAddresses) } + + $aliases = $existing | Where-Object { $_ -notlike "SMTP:*" } + + $aliases = $aliases | Select-Object -Unique + + $newProxy = @($newPrimary) + $aliases + + if (-not $existing -or ($existing -join "|") -ne ($newProxy -join "|")) { + $changes += "proxyAddresses updated" + if (-not $DryRun) { + Set-ADUser $u -Replace @{ proxyAddresses = $newProxy } + } + } + } + + if ($FixUPN -and $u.userPrincipalName -ne $desiredUPN) { + $changes += "UPN → $desiredUPN" + if (-not $DryRun) { + Set-ADUser $u -UserPrincipalName $desiredUPN + } + } + + if ($changes.Count -gt 0) { + Write-Host "$($u.sAMAccountName): $($changes -join ', ')" -ForegroundColor Green + } else { + Write-Host "$($u.sAMAccountName): no changes needed" -ForegroundColor DarkGray + } +} + +Write-Host "Done." -ForegroundColor Cyan +