Files
Windows-Admin-Scripts/FixDomainEmails/FixDomainEmails.ps1
2026-01-22 11:46:52 -06:00

76 lines
1.9 KiB
PowerShell

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