email fix script
This commit is contained in:
75
FixDomainEmails/FixDomainEmails.ps1
Normal file
75
FixDomainEmails/FixDomainEmails.ps1
Normal file
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user