Copy AD Group membership from series of groups to new groups

I have 30 AD security groups, each with their own membership. The group names are formatted as follows:

My-Contoso-Group1, My-Contoso-Group2, My-Contoso-Group3, etc. There are 30 or so groups all named this way with the only variable being the string after “Contoso-”.

I scripted a process to create a new set of groups, with the following names:

My-Fabrikam-Group1, My-Fabrikam-Group2, My-Fabrikam-Group2, etc.

The group membership for each Fabrikam group needs to match that of the corresponding Contoso group.

I came up with the following, but it is not fully automated since the ‘$var’ variable needs to be manually updated for each group:

 


#Import the group names

$gname = get-content c:\temp\groupsourcefile.txt

#Remove the prefix from the name, leaving only the variable

$gvar = ($gname -split "Contoso-")[4].substring(0).trimEnd()

#Specify the source and target groups

$gSource = "CN=My-Contoso-$gvar,OU=Groups,DC=contoso,DC=com"

$gTarget = "CN=My-Fabrikam-$gvar,OU=Groups,DC=contoso,DC=com"

#Add the group members to the target group

$target = Get-AdGroupMember -Identity $gSource `

foreach ($person in $target) `

{ Add-ADGroupMember -Identity $gTarget -Members $person.distinguishedname }

This works just fine, but as already mentioned, it requires manually intervention to change the variable. Can this be fully automated so that it reads the file, gets each variable and updates the group membership of the target group accordingly?

Regards,

edit: removed errant ‘$var’ variable.

 

Looking at the code provided - I don’t see where $var is used (unless there was more code that wasn’t included?)

That being said - do something like the following in a foreach loop

foreach ($item in Import-Csv c:\temp\groupsourcefile.csv)
{
$gname = $item.name

#Remove the prefix from the name, leaving only the variable
$gvar = ($gname -split "Contoso-")[4].substring(0).trimEnd()

#Specify the source and target groups
$gSource = "CN=My-Contoso-$gvar,OU=Groups,DC=contoso,DC=com"

$gTarget = "CN=My-Fabrikam-$gvar,OU=Groups,DC=contoso,DC=com"

#Add the group members to the target group
$target = Get-AdGroupMember -Identity $gSource

foreach ($person in $target)
{
Add-ADGroupMember -Identity $gTarget -Members $person.distinguishedname
}
}

where each of the groups you need to work with is one line of the csv file and the csv file has a header of name

Just a quick and dirty example of what you can do - adding in a loop around the code you already wrote