Distribution list update using Powershell ForEach Statement

60 Views Asked by At

I am trying to run the below command. This command should find all active mailboxes from exchange online that have the @hhh.co.uk email address and then update the distribution list with the email addresses found.

Upon running this command the script runs fine and updates the Distribution list but there are inactive/sign in blocked users and shared mailboxes appearing in the distribution list, there is a leaver OU setup in AD and the environmwnt is multi domain otherwise I would use a dynamic Distribution list, just so you have all of the information I have. Would anyone be able to point me in the right direction with the script please?

$users = Get-EXOMailbox -ResultSize Unlimited -Filter {(EmailAddresses -like "*hhh.co.uk") -and           (IsMailboxEnabled -eq $True)} | Select UserPrincipalName, PrimarySmtpAddress


foreach($user in $users)
{
If ($user.PrimarySmtpAddress -like "*hhh.co.uk")
    {
    write-host $user.UserPrincipalName", "$user.PrimarySmtpAddress
    Add-DistributionGroupMember –Identity "[email protected]" -Member $user.PrimarySmtpAddress -ErrorAction       SilentlyContinue
    }
}
0

There are 0 best solutions below