Had the same problem (a bit late) so I took your "script" and updated it. You need to disable email address policy to be applied to contacts in Exchange and it will partially solve the problem.
1) Expand Microsoft Exchange On-Premises
2) Expand Organization Configuration
3) Select Hub Transport and go to Email Address Policies Tab
4) Edit each one leaving Users with external e-mail addresses
without check box and Contacts with external e-mail addresses
.
![enter image description here](../../images/3829730439.webp)
It will partially solve the problem because the default policy can't be disabled so I ended up having domain.local email addresses by default added to new contacts anyway.
So I wrote a script based on the one provided in question (the one in question had some bugs where multiple addresses from same domain were assigned and it was making a lot of noise) that will remove any email addresses that are not external and it will also make sure the old contacts won't get policies reapplied.
####
# Input variables
####
$domains = @("*@domain.com","*@domain.pl","*@evotec.pl", "*@domain.local")
$ou = "evotec.local"
####
# Removing internal domains from contacts
####
$domains | foreach {
$domain = $_;
write-host "Preparing for removal of addresses with domain name:" $domain
$Contacts = Get-MailContact -OrganizationalUnit $ou -Filter {
EmailAddresses -like $domain -and name -notlike "ExchangeUM*"
} -ResultSize unlimited -IgnoreDefaultScope
$Contacts | foreach {
$contact = $_;
$email = $contact.emailaddresses;
#write-host "1. " $contact
#write-host "2. " $contact.name
#write-host "3. " $email
#write-host "4. " $contact.identity
$email | foreach {
if ($_.smtpaddress -like $domain)
{
$address = $_.smtpaddress;
write-host "[*] Removing address" $address "from Contact" $contact.name;
Set-Mailcontact -Identity $contact.identity -EmailAddresses @{Remove=$address};
}
}
}
}
####
# Setting up email address policy to disabled for all contacts
####
write-host "Preparing all contacts for disabling email address policy"
$Contacts = Get-MailContact -OrganizationalUnit $ou -Filter {
EmailAddresses -like $domain -and name -notlike "ExchangeUM*"
} -ResultSize unlimited -IgnoreDefaultScope | Where {$_.EmailAddressPolicyEnabled -eq $true}
$Contacts | foreach {
$contact = $_;
write-host "[*] Setting up email address policy to disabled for" $contact.name
$contact | set-mailcontact -emailaddresspolicyenabled $false
}
The final step is to set it up as Task Scheduler as new contacts will keep on getting the non-editable (in supported way at least) default policy. This setup at Exchange server will run just fine. Make sure to run it with correct permissions.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; C:\ExchangeScript\RemoveLGBSEmailsFromContacts.ps1"