Reputation: 23
I'm relatively new to PowerShell and am trying to learn it for a project at work involving Active Directory. The task I have is to compare the members of two different security groups in AD (both groups are located in the same OU) and copy the members from Group 2 that are not in Group 1 over to Group 1.
I came across this link that showed how to compare groups but:
Upvotes: 2
Views: 20579
Reputation: 61
Given two security groups, DestinationGroup (Group 1), SourceGroup (Group 2):
Add-ADGroupMember -Identity "DistinguishedName of DestinationGroup" -Members (Get-ADGroupMember -Identity "DistinguishedName of SourceGroup" | Select-Object -ExpandProperty distinguishedName)
Upvotes: 1
Reputation: 1018
I found another solution which is very easy that I could not resist to share with you all:
Get-ADGroupMember -Identity GROUP-A | Add-ADPrincipalGroupMembership -MemberOf GROUP-B
Get-ADGroupMember
gets all the members of GROUP-A and pipes into Add-ADPrincipalGroupMembership
cmdlet that added the incoming members to GROUP-B.
Upvotes: 1
Reputation: 1990
Here you go. Try the below script which I have written for your requirement.
#Input Parameters. Change these as per your requirement
$group1 = "Group1Name"
$group2 = "Group2Name"
$membersInGroup1 = Get-ADGroupMember $group1
$membersInGroup2 = Get-ADGroupMember $group2
if($membersInGroup1 -eq $null)
{
Add-ADGroupMember -Identity $group1 -Members $membersInGroup2
}
elseif($membersInGroup2 -ne $null)
{
$separateMembers = diff $membersInGroup1 $membersInGroup2
if($separateMembers -ne $null)
{
foreach($member in $separateMembers)
{
$currentUserToAdd = Get-ADUser -Identity $member.InputObject
Add-ADGroupMember -Identity $group1 -Members $currentUserToAdd
}
}
}
Let me know if you face any issues.
Upvotes: 2