powershellexchange-server

Filter recipients on having email address(es) from an array of email domains


Looking to see if I can streamline gathering recipients (via Get-Recipient) who have at least one email address that belongs to an array of email domains. We have a divestiture coming up where we'll need to scrub these email addresses from our hybrid Exchange 2016/EXO environment (our on-prem AD is still authoritative, so everything is being run from Exchange 2016 and not the cloud). My question is about gathering the collection of these users into an array that I can then work with to do the clean up.

This business unit literally has hundreds of email domains, which I have available as an array ($domains). I know I can loop through this list looking for recipients having each particular email domain one domain at a time, but that seems inefficient.

Is there a way to leverage my array of domains and use -Contains to check each recipient for any of those domains in one shot? I've tried the below, but my logic is faulty it seems:

$List = $Recipients | where {$domains -contains (($_.EmailAddresses.AddressString).split("@")[-1])}

I only got 7 items (one mailbox, 6 public folders), where there should be hundreds of recipients so I'm not parsing the multivalued EmailAddresses attribute correctly.

The desired end result is an array that contains the recipients that have at least one smtp address from a domain in the $domains array.


Solution

  • To efficiently address this issue, initiate the Get-Recipient command once and store its output in a temporary CSV file. This file can then be used for parsing and subsequent variable constructions as required.

    This approach minimizes the number of interactions with the Exchange Online cloud, ensuring that the data is retrieved only once and is readily accessible on the local file system for subsequent queries.

    You can also concatenate your "domains" array with a pipe character to create another variable. This variable can then be referenced using the -match operator instead of -contains to list matching domains.

    PowerShell

    $tmpCsv = "C:\Test\Get-Recipient-Dump.csv";
    $domains = @("domain1.com","domain2.org","domain4.com");
    $domains = $domains -join "|";
    
    Get-Recipient -ResultSize Unlimited | Export-csv $tmpCsv -NoTypeInformation;
    
    Import-Csv -Path $tmpCsv | 
        Where-Object {$_.EmailAddresses -match $domains} |
            Select DisplayName, EmailAddresses;
    

    Supporting Resources