Home > Net >  How can I get group members from an AD group that only contains security groups?
How can I get group members from an AD group that only contains security groups?

Time:02-11

I have 3 groups (HR, COMPT and FIN) and their groups contains only security groups. How do I extract their members of their groups?

$Groups = 
@"
GroupNames;
HR
COMPT
FIN
"@ | ConvertFrom-Csv -Delimiter ';'

#HR has 3 security groups
#COMPT has 5 security groups
#FIN has 2 security groups
### I want to know how can I get their members ###

foreach ($Group in $Groups){
#Save-File to this Path
$Path = "C:\Temp\"

$group.GroupNames | Get-ADGroupMember | select name -ExpandProperty Name | ForEach-Object { 
Get-ADGroup $_ -Properties Members | select Name |
#Export CSV
Export-Csv -Path (Join-Path -Path $path -ChildPath ('{0}.csv' -f $group.Name)) -NoTypeInformation -Delimiter ";" -Encoding UTF8

  }
}

CodePudding user response:

You can try something like this, first you loop through the groups on the CSV (Parents), then for each parent you query their Member attribute (Child Groups) and for each child you query their Member attribute which should be in this case users objects. This would give you a report of each Parent Group and their Child Groups and their Members.

# CSV Should have a `GroupNames` column!!
$groups = Import-Csv /path/to/parentGroups.csv

$result = foreach($parent in $groups.GroupNames) {
    $parentGroup = Get-ADGroup $parent -Properties Member
    foreach($child in $parentGroup.Member) {
        # NOTE: This assumes the Members of Parent are GROUPS!
        $childGroup = Get-ADGroup $child -Properties Member
        foreach($member in $childGroup.Member) {
            $member = Get-ADObject $member
            [pscustomobject]@{
                ParentGroup = $parentGroup.SamAccountName
                ChildGroup  = $childGroup.SamAccountName
                Member      = $member.SamAccountName
                ObjectClass = $member.ObjectClass
            }
        }
    }
}

$result | Export-Csv ..... -NoTypeInformation
  • Related