How to copy members from one security group to another security group in AD using PowerShell v4?
16,310
Solution 1
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.
Solution 2
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)
Related videos on Youtube
Author by
Peach
Updated on September 15, 2022Comments
-
Peach over 1 year
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:
- The code segment listed on this website returns both the members from Group 1 that aren't in Group 2 and the members from Group 2 that aren't in Group 1 which is way more information than I need
- Once I get the list I don't know how to use that to enter into a command or script to copy those members to the appropriate group.
-
Aman Sharma almost 8 yearsAs you are new, if this resolves your issue, please accept this as answer by clicking on the tick mark under the arrows, beside my answer.
-
Peach almost 8 yearsThanks for the help. The script worked perfectly. I don't know if I totally understand how part of the script worked, but I'm sure in time with working with PowerShell, it will make more sense eventually.