Need to retrieve all groups and nested groups that a bulk of users from an OU belong to

New Contributor

I already build this script that retrieve users and groups membership, but i also need all the nested group that each users belong to


Get-ADUser -Filter * -SearchBase "OU=Users,OU=Test,DC=test,DC=com" -Properties memberOf |
# $_ represents a user object
$var = [PSCustomObject]@{
SID = $_.SamAccountName
Name = $_.Name
Group = ""
# create one row for each user, all groups in "Group" column, each separated by ';'
if ($_.memberOf){
$groups = @()
$_.memberOf |
$groups += (Get-ADGroup $_).samaccountname
$var.Group = $groups -join ';'

} | Export-Csv -Path C:\powershell\Lac-UsersWithGroups.csv -NoTypeInformation

3 Replies
best response confirmed by Slypink (New Contributor)

@Slypink I changed your script a little ;) Ran this on my test Domain Controller:



$total = foreach ($user in Get-ADUser -Filter * -SearchBase "DC=test,DC=local" | Sort-Object Name) {
    $groups = (Get-ADUser -SearchScope Base -SearchBase $user.DistinguishedName -Filter * -Property msds-memberOfTransitive | Select-Object msds-memberOfTransitive).'msds-memberOfTransitive'
        SamAccountName = $user.SamAccountName
        Name           = $user.Name
        Groups         = (($groups | Get-ADGroup).name | Sort-Object) -join ';'

$total | Export-Csv -Path C:\scripts\Lac-UsersWithGroups.csv -NoTypeInformation -Delimiter ';' -Encoding UTF8



This returns a CSV file containing :



"admin";"Admin Account";"Administrators;Denied RODC Password Replication Group;Domain Admins"
"Administrator";"Administrator";"Administrators;Denied RODC Password Replication Group;Domain Admins;Enterprise Admins;Group Policy Creator Owners;Schema Admins"
"krbtgt";"krbtgt";"Denied RODC Password Replication Group"
"serviceaccount";"Service Account";""
"user1";"User 1";"Group1;Group2"
"user2";"User 2";"Group1;Group2"
"user3";"User 3";"Group2"
"user.4";"User 4";"Administrators"



Just change the SearchBase and CSV path and you're good to go, let me know if this works out for you!

@Harm_Veenstra This is exactly what i need, and it work very well

So thanks you very much for this



No problem, glad to hear that :smiling_face_with_smiling_eyes:please mark my answer as solution to mark this as solved