Forum Discussion
kleblanc4951
Sep 14, 2022Copper Contributor
Powershell to compare groups and add users based on comparison
I am not a script writer and I'm looking for a way to take a security group that was created in Azure AD and update a distribution group with any additions/deletions made to that group. The situatio...
AndySvints
Nov 17, 2022Iron Contributor
Hello kleblanc4951,
You can use Compare-Object and then based on the SideIndicator remove or add members to Distribution list.
Quick and dirty way would be something like this:
$AzADGroup=Get-AzureADGroupMember -ObjectId "73a2e3e3-21f2-4856-8651-4a03a980014f" -All $true | select DisplayName, UserPrincipalName
$DL=Get-DistributionGroupMember -Identity "iPhone Notifications" | select Identity, PrimarySMTPAddress
$Comparison=Compare-Object -ReferenceObject $AzADGroup.UserPrincipalName -DifferenceObject $DL.PrimarySMTPAddress
foreach ($i in $Comparison){
if($i.SideIndicator -eq "=>"){
#Listed in DL but not in AzureADGroup
#Remove from DL membership
Write-output "Remove $($i.InputObject) from DL"
}elseif($i.SideIndicator -eq "<="){
#Listed in AzureAd but not in DL
#Add to DL Membersip
Write-output "Add $($i.InputObject) to DL"
}
}
Hope that helps.
kleblanc4951
Nov 22, 2022Copper Contributor
Thanks so much for the information! I will play around with that for a bit and see what I can do. For the moment I'm exporting the list of members from the security group then using Update-DistributionGroupMember to update the distribution group by importing the list.