'genrate an overview of ADnested groups in excel

I need some help with a powershell script to export AD users of a nested group to csv. Situation: I’ve an ad group, with one or more nested groups. I want to export the users to a csv file showing the nested group they a members of. Example: Group A contains Group B and users. Group B contains group C, D, E and also users I want an output like this: User1 is member of Group D which is member of group B witch is member of group A User2 is member of Group C which is member of group B witch is member of group A User6 is member of Group B which is member of group A User14 is member of Group C and E which is member of group B witch is member of group A Etc. in csv it should look likes this.

|UserName |group |group |GroupName |User1 |D |B |A |User2 |C |B |A |User6 |B |A |User14 |C, E |B |A

I have created the following script.

#Get ADGroup A
$ADGroups = get-adGroup -filter 'name -like "Group A"' 
#Get ADGroups A include nested groups and ther members also create a Output file
$output = @()
$ADGroups | foreach {
$groupName = $_.name
$groupMembers = $_ | get-adGroupMember -Recursive
$groupMembers | foreach {
$memberName = $_.name
$obj = new-object System.Management.Automation.PSObject
$obj = $obj | add-member -memberType NoteProperty -name groupName -value $groupName -passthru
$obj = $obj | add-member -memberType NoteProperty -name userName -value $memberName -passthru
$output += $obj
}
}
$output
$output | export-csv "c:\temp\overview.csv" -NoTypeInformation -Append 

The output is the user in the group A only, not showing the real nested group where the user is member of. groupName userName A User1 A User1 A User2 A User1



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source