Forum Discussion
Sam240
Apr 01, 2022Copper Contributor
Users not part of office distribution lists PowerShell
I'm looking to find office365 users whose primary SMTP is our domain.com that are not part of certain office365 distribution lists we have. For example Dist1, Dist2, Dist3, Dist4 and export the resul...
Apr 02, 2022
Sam240 I created this one in my test tenant:
Script:
Connect-ExchangeOnline
$total = @()
$users = Get-Mailbox | Where-Object PrimarySmtpAddress -Match 'M365x537152.OnMicrosoft.com' | where-object PrimarySmtpAddress -NotMatch 'DiscoverySearchMailbox' | Sort-Object UserPrincipalName
$distributiongroups = "Executives", "Sales Team", "Tailspin Toys"
foreach ($distributiongroup in $distributiongroups) {
$distributiongroupmembers = Get-DistributionGroupMember -Identity $distributiongroup
foreach ($user in $users) {
if (-not ($distributiongroupmembers | Select-String $user.name)) {
$output = [pscustomobject]@{
"DistributiongroupName" = $distributiongroup
"UserName which is not a Member" = $user.UserPrincipalName
}
$total += $output
}
}
}
$total | Export-Csv -Path c:\temp\distributiongroups.csv -NoTypeInformation -Delimiter ';'
CSV:
- Newbie_JonesMay 16, 2022Brass ContributorWhy the two client side filters in the Get-Mailbox line? Performance wise that looks strange.
Can't we use a server side filter on Get-Mailbox for the two PrimarySmtpAddress elements?- May 16, 2022
You can use whatever filter you want 😉 I added the discoverymailbox because it was also evaluated, you can leave that out if you want.. Performance wise there was no impact in my test environment, very few users, but in larger environments it could take somewhat longer. But is this something you run once in a while or daily?
Shorter version:
Get-Mailbox | Where-Object {$_.PrimarySmtpAddress -Match 'M365x537152.OnMicrosoft.com' -and $_.PrimarySmtpAddress -NotMatch 'DiscoverySearchMailbox'} | Sort-Object UserPrincipalName- Newbie_JonesMay 17, 2022Brass Contributor
Can't this all be done server side.
Get-Mailbox -Filter {$_.PrimarySmtpAddress -Match 'M365x537152.OnMicrosoft.com' -and $_.PrimarySmtpAddress -NotMatch 'DiscoverySearchMailbox'} | Sort-Object UserPrincipalName
- Sam240Apr 06, 2022Copper Contributor
Harm_Veenstra Thank you so much. I'll test it out and get back to you but this looks like it might do it for me!!!
- May 14, 2022Please mark my answer as solution to mark it as solved if it worked out for you.
- Apr 11, 2022
Did it work for you ?
- Apr 06, 2022
No problem, let us know if it works out for you!