I have a script that pulls all the members of a group and copies those members to another group.
It takes roughly an hour to run so I was hoping to be able to just pull any members who are not already in the second group.
Is there an easy way to add that to the script I already have?
Specifically is it possible to compare the two groups and only write the members who are not already in it.
$ExistingMembers = Get-AzureADGroup -ObjectId xxxxxxxxxxxxxxxxx | Get-AzureADGroupMember -All $True
Foreach ($Member in $ExistingMembers){
Add-AzureADGroupMember -ObjectId xxxxxxxxxxxxxxx -RefObjectId $Member.ObjectId
}
CodePudding user response:
I tried to reproduce the same in my environment for me it's working fine with short span of time,The reason behind latency may be because of having more member in your group.
Try using below PowerShell code, if u have more then 100 members in your group
$group1 = "ObjectId pulled from AAD"
$group2 = "ObjectId pulled from AAD"
$membersGroup1 = Get-AzureADGroupMember -ObjectId $group1 -All $true
foreach($member in $membersGroup1)
{
$currentuser = Get-AzureADUser -ObjectId $member.ObjectId | select objectid
Add-AzureADGroupMember -ObjectId $group2 -RefObjectId $currentuser.objectid
}
Added a group member
After running the above script, members in group 1 added to group 2 successfully in short time.
For your Reference :
Azure ad add member from one group to another
CodePudding user response:
Not sure if this will be faster but you can give it a try and let me know, though for sure, this code will not attempt to add a member if the member is already there.
The logic is to first get all members of the destination group and store their ObjectId
in a HashSet<T>
, this helps us avoid adding a new member already there.
Note that the order here is reversed from your script, instead of getting the membership of the source group first, we get the members of the destination.
# This is the Group you're about to Add new Members (Destination)! The order is reversed here
[Collections.Generic.HashSet[Guid]] $guids = (Get-AzureADGroupMember -ObjectId xxxx -All $True).ObjectId
# Loop through the Source Group
foreach($member in Get-AzureADGroupMember -ObjectId yyyy -All $True) {
# if this member does not exist in the Destination group
if($guids.Add($member.ObjectId)) {
# add it
Add-AzureADGroupMember -ObjectId xxxx -RefObjectId $member
}
}