Get recursive group membership of all AD users using Powershell

Phoneutria picture Phoneutria · May 27, 2014 · Viewed 47k times · Source

I'm trying to make a PS script which would list all Active Directory user group membership (recursive).

I already have working script:

import-module activedirectory

$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' } 

$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"


foreach ($user in $users)
{
    $groups = Get-ADPrincipalGroupMembership $user

    foreach ($group in $groups)
    {
        $username = $user.samaccountname
        $groupname = $group.name
        $line = "$username;$groupname"
        Add-Content $targetFile $line
    }
}

But script doesn't list groups recursively, i.e., if group listed in the output file is part of another group.

Example:

Group1: User

Group2: Group3: User

Script shows only Group1 and 3 but not 2.

What should I add to the first script that it writes group membership recursively?

Answer

E235 picture E235 · Oct 1, 2017

Sorry I am publishing an answer for a question from 3 years ago but if someone will see it, it can help.
Credit to:
How to get ALL AD user groups (recursively) with Powershell or other tools?

You can use the LDAP_MATCHING_RULE_IN_CHAIN:

Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=CN=User,CN=USers,DC=x)"

You can use it anywahere that you can use an LDAP filter.

Example:

$username = 'myUsername'
$dn = (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) | select -expand Name | sort Name  

Fix in your script:

import-module activedirectory

$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' } 

$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"

foreach ($user in $users)
{
$dn = $user.DistinguishedName
    $groups = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) | select -expand Name | sort Name

    foreach ($group in $groups)
    {
        $username = $user.samaccountname
        $groupname = $group.name
        $line = "$username;$groupname"
        Add-Content $targetFile $line
    }
}