List ActiveDirectoryGroups for a user, using PowerShell

Published on Tuesday, 24 October 2023

If one needs to know the AD Groups a given user is a member of, there are several ways. Some of them are described in an old TechNet article. Another method that is very easily used in PowerShell is ADSI mainly because it is part of every PowerShell and no aditional installation is needed.

Getting the direct groups a user is a member of is as easy as running

([adsisearcher]"cn=Andresen\, Nils").findone().properties.memberof

To fetch all (transitive) groups that a user is a member of, is slightly more complicated:

function Get-UserGroups ($search) {
  $u = ([adsisearcher]$search).findone()

  $tmp = New-Object System.Collections.Stack
  $tmp.Push($u.Path)

  while ($tmp.count -gt 0) {
    $curr = $tmp.Pop()
	$obj = ([adsi]"$curr")
    $o = [pscustomobject] @{
      Name = "$($obj.properties.cn)";
      Path = "$($obj.path)";
    }
    Write-output $o
    ([adsi]"$curr").properties.memberof | % {
	  if(![string]::isnullorempty($_)) {
        $tmp.Push("LDAP://$_")
	  }
    }
  }
}

Using this function, it is possible to list the groups using

Get-UserGroups "cn=Andresen\, Nils"