powershellmemberadsidirectorysearcher

How to look for members of a group or object with adsi


The company has an AD structure that I need to search for the groupnames where the user is member. I do know it should be in the "memberof" attribute for the users, let's just say that is not always correct.

I tried the below code to find the username (or objectname) within the "members" attribute for all of the groups within an OU and then bring back the name of the group. Unfortunately I think I am missing something. Reverse search (IE: listing the members of a group) is working, but in my case I do not know the name of the groups. Also I need all of the groups, not just a single.

uname ="*anyoldusername*"

$Searcher = [ADSISearcher]"(member=$uname)"
$Searcher.SearchRoot = [ADSI] "LDAP://mydomainsearchroot"
$Searcher.PageSize = 10000
$result = $Searcher.FindAll().Properties.cn

echo $result

Solution

  • This should do it:

    $UserName ="TestUser"
    $Searcher = [ADSISearcher]""
    $Searcher.SearchRoot = [ADSI]"LDAP://mydomainsearchroot"
    $Searcher.Filter = "Name=$UserName"
    $UserDN = $Searcher.FindOne().properties.distinguishedname
    $Searcher.Filter = "(member:1.2.840.113556.1.4.1941:=$UserDN)"
    $Searcher.PageSize = 10000
    $result = $Searcher.FindAll().Properties.cn
    $result
    

    The first search is to find the DN of the user, since that's required for the filter in the next search. To read more about the "1.2.840.113556.1.4.1941" filter see this documentation.

    Oh, and echo is an alias for Write-Output in Powershell, better to use that directly or even omit it entirely since a string or variable on it's own will default to Write-Output anyway as you can see when $result is run at the end.