Here is a script I had to put together to remove all e-mail addresses containing a specific domain (“contoso.com” in this example) on all your objects in your on-prem AD.
Naturally this script can’t be altered to only include a specific subset of users, just change the “get-adobject” to match.
What sets this script apart from all the others you can find out there on the Internet is that this uses on-prem AD. Reason for this is that a lot of organizations out there are using their on-prem AD to sync their users and groups and not all of them have complete on-prem Exchange infrastructure to manage this so using this seemed a lot better. At least it did for us.
Of course this script writes to the console what it does every step of the way and it writes to date stamped transcript, making tracing and rollbacks easy-ish.
It won’t remove the e-mail address if it’s a primary e-mail since that may cause issues but it will flag it in red so pay attention to your console or search the transcript for “primary”.
$DateStamp = Get-Date -Format "yyyy-MM-dd-HH-mm-ss"
$Logfile = $LogFile = ("c:\temp\removing_mail_addresses-" + $DateStamp + ".txt")
start-transcript $logfile
$Mailboxes = Get-adobject -Filter {proxyAddresses -like "*contoso.com"} -Properties *
foreach($mailbox in $Mailboxes)
{
$DN = ""
$upn = ""
$DN = $mailbox.DistinguishedName
$upn = $mailbox.UserPrincipalName
write-host "Processing User $upn ..."
$i=0
while($i -lt $mailbox.proxyAddresses.Count)
{
$address = $mailbox.proxyAddresses[$i]
write-host -NoNewline "Processing mailadress $address..."
if ($address -clike "smtp:*" -and $address -like "contoso.com" )
{
write-host -ForegroundColor Yellow " removing address"
Set-ADObject -identity $dn -remove @{ProxyAddresses=$address}
$i--
}
elseif($address -clike "SMTP:*" -and $address -like "*contoso.com" ) { write-host -ForegroundColor Red " MAIL ADDRESS IS PRIMARY!" }
else { write-host -ForegroundColor Green " no action taken." }
$i++
}
write-host "---------------------------------------------------------------"
}
Stop-Transcript