Finding groups a user is member of

The following code sample outputs a list of groups a user is a direct member of.

ADSI
[Reflection.Assembly]::LoadWithPartialName("Softerra.Adaxes.Adsi")

# Connect to the Adaxes service
$ns = New-Object("Softerra.Adaxes.Adsi.AdmNamespace")
$service = $ns.GetServiceDirectly("localhost")

# Bind to the user
$userDN = "CN=John Smith,CN=Users,DC=domain,DC=com"
$user = $service.OpenObject("Adaxes://$userDN", $null, $null, 0)

foreach ($groupGuidBytes in $user.Get("adm-DirectMemberOfGuid"))
{
    $groupGuid = New-Object "System.Guid" (,$groupGuidBytes)
    $groupGuid = $groupGuid.ToString("B")
    $groupPath = "Adaxes://<GUID=$groupGuid>"
    $group = $service.OpenObject($groupPath, $null, $null, 0)
    Write-Host $group.Name
}
PowerShell
Import-Module Adaxes

$identity = "jsmith" # sAMAccountName
# $identity = "CN=John Smith,CN=Users,DC=domain,DC=com"  # DN
# $identity = "{EB5FEB21-E648-42AD-B86C-89D3C6807953}" # GUID
# $identity = "S-1-5-21-573937-2149998-410785" # SID

$groups = Get-AdmPrincipalGroupMembership -Identity $identity -Server "domain.com" `
    -AdaxesService localhost
    
foreach ($group in $groups)
{
    Write-Host $group.Name
}

The following code sample outputs a list of all groups a user is a member of (via direct and indirect membership).

ADSI
[Reflection.Assembly]::LoadWithPartialName("Softerra.Adaxes.Adsi")

# Connect to the Adaxes service
$ns = New-Object("Softerra.Adaxes.Adsi.AdmNamespace")
$service = $ns.GetServiceDirectly("localhost")

# Bind to the user
$userDN = "CN=John Smith,CN=Users,DC=domain,DC=com"
$user = $service.OpenObject("Adaxes://$userDN", $null, $null, 0)

foreach ($groupGuidBytes in $user.Get("adm-MemberOfGuid"))
{
    $groupGuid = New-Object "System.Guid" (,$groupGuidBytes)
    $groupGuid = $groupGuid.ToString("B")
    $groupPath = "Adaxes://<GUID=$groupGuid>"
    $group = $service.OpenObject($groupPath, $null, $null, 0)
    Write-Host $group.Name
}
PowerShell
Import-Module Adaxes

$identity = "jsmith" # sAMAccountName
# $identity = "CN=John Smith,CN=Users,DC=domain,DC=com"  # DN
# $identity = "{EB5FEB21-E648-42AD-B86C-89D3C6807953}" # GUID
# $identity = "S-1-5-21-573937-2149998-410785" # SID

$groups = Get-AdmPrincipalGroupMembership -Identity $identity -Server "domain.com" `
    -Recursive -AdaxesService localhost
    
foreach ($group in $groups)
{
    Write-Host $group.Name
}

See also