Forum Discussion
JoshuaLance
Aug 07, 2024Copper Contributor
List users not in distribution lists
I am looking for a way to list all users that are not in 8 specific distribution lists.
I have found an option that gets close but it is not correct.
I only want to display the users that are not in list 1, or list 2, or list 3, or list 4, or list 5 or list 6 or, list 7, or list 8.
The script I found does not appear to apply the "or" to the query.
I also need it to export to a file rather than display on the screen.
Here is a copy of the syntax I found.
$Users = Get-Mailbox | ? {$_.PrimarySmtpAddress -like "*MyDomain.com"} #Enter your domain
$DistributionGroups = @("List 1","List 2","List 3","List 4","List 5","List 6","List 7","List 8") #Enter names of your distributiongroups
foreach($DistributionGroup in $DistributionGroups)
{
$DistributionGroupMembers = Get-DistributionGroupMember $DistributionGroup
foreach($User in $Users)
{
foreach($DistributionGroupMember in $DistributionGroupMembers)
{
if($DistributionGroupMember.PrimarySmtpAddress -ne $User.PrimarySmtpAddress)
{
Write-Host "$($User.PrimarySmtpAddress) missing in $DistributionGroup" #Export output here fx.
}
}
}
}
2 Replies
Sort By
- The correct way of doing this will be with a server-side filter and the MemberOfGroup property. Unfortunately, it only works against the DN of the group, so you need to fetch those first. Here's an example:
Get-Mailbox -Filter "MemberOfGroup -ne 'CN=DG1,OU=tenant.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR03A001,DC=prod,DC=outlook,DC=com' -and MemberOfGroup -ne 'CN=DG2,OU=tenant.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR03A001,DC=prod,DC=outlook,DC=com'"
The example is just for 2 DGs, add similar entries for the rest.- JoshuaLanceCopper ContributorThanks for the response.
I will give this a try and let you know how it goes.