I am trying to copy multiple users from a pair of 2 or 3 groups to one new group. There are 30 groups which needs to be moved to 10 new groups.
Example:
Oldgroup1, Oldgroup2, Oldgroup3 > NewGroup1
Oldgroup4, Oldgroup5 > NewGroup2
I am thinking of foreach loop but can not figuer out how to bind multiple old groups to new group as members from old groups can be diff.
CodePudding user response:
Organize the mapping between new and old groups in a dictionary:
$groupMappings = @{
'NewGroup1' = 'Oldgroup1', 'Oldgroup2', 'Oldgroup3'
'NewGroup2' = 'Oldgroup4', 'Oldgroup5'
}
Then for each mapping entry:
- Fetch the members of the old groups
- Remove duplicates from result
- Add them to the new group
foreach($entry in $groupMappings.GetEnumerator()){
# Fetch members of all the old groups, keep only unique set of users
$members = $entry.Value |Get-ADGroupMember |Where-Object objectClass -eq user |Sort-Object -Unique objectGUID
# Add them all, one by one (this way the whole request wont fail if any one member is already a member of the target group)
foreach($member in $members){
Add-ADGroupMember -Identity $entry.Name -Member $member
}
}