This post follows on from my earlier post with a script to remove Domains from Exchange On-Premises. If you haven’t read that yet, you can find it here.
After realising that I had users in my Exchange environment that were using domains that were not added as accepted domains in Office 365, I worked out a way to remove them from Exchange On-Premises (see above post) but I hadn’t got an easy way of identifying the domains that I needed to remove. So I wrote some quick PowerShell to get me a list from my users that were synchronised to Office 365.
After creating a variable to store my output to be fed back at the end of the script, I first pull the list of Accepted Domains in Office 365 to compare against, all mail users from my tenant, to compare their addresses, and count the number of domains I need to iterate through:
$Output = @()$domains = (Get-AcceptedDomain).DomainName$Users = Get-MailUser -ResultSize Unlimited$TotalDomains = $domains.Count
I then use a ForEach look to go through each user in turn, examine their email addresses, and if one of them does is not one of the Office 365 accepted domains, add it to my list of domains for the output.
foreach ($User in $Users){$MailUser = $Userforeach ($ProxyAddress in $MailUser.EmailAddresses){$proxyAddressDomain = (($ProxyAddress -split '@')[1])IF($ProxyAddressDomain -ne $Null){if ($Domains -notcontains $proxyAddressDomain.Trim(' ')){$Output += (($ProxyAddress -split '@')[1])}}}}
Once this is complete I return the de-duplicated list of domains to be picked up and remediated later:
$Output | Select -Unique
This isn’t the sort of problem you will come across very often. It is rare to find an Exchange environment where old/unused domains are used in such volume to make this sort of automation necessary, but this could be handy should you come across the problem in the future!
The whole script is available below:
$Output = @()$domains = (Get-AcceptedDomain).DomainName$Users = Get-MailUser -ResultSize Unlimited$TotalDomains = $domains.Countforeach ($User in $Users){$MailUser = $Userforeach ($ProxyAddress in $MailUser.EmailAddresses){$proxyAddressDomain = (($ProxyAddress -split '@')[1])IF($ProxyAddressDomain -ne $Null){if ($Domains -notcontains $proxyAddressDomain.Trim(' ')){$Output += (($ProxyAddress -split '@')[1])}}}}$Output | Select -Unique
If you have any questions or comments please either use the comments section below, Tweet me @MikeParker365 or via email blog@mikeparker365.co.uk.