Lima
Lima

Reputation: 1211

Active Directory User Group Membership

I am trying to get a users group membership and limiting the results to those that match a string, ie I am only interested in the users group membership where the group begins with "test-".

The following is what I have been playing around with, even though the user is apart of several groups that match the search string, the If statement is not returning True on any of them.

Private Function GetGroups(ByVal userName As String) As Collection
    Dim Groups As New Collection
    Dim intCount As Integer
    Dim entry As DirectoryEntry = ADEntry()
    Dim mySearcher As DirectorySearcher = New DirectorySearcher(entry)
    Dim arrList As New ArrayList()

    ' Limit the search results to only users
    mySearcher.Filter = "(&(ObjectClass=User)(CN=" & userName & "))"
    ' Set the sort order
    mySearcher.PropertiesToLoad.Add("MemberOf")

    Dim searchResults As SearchResultCollection = mySearcher.FindAll()
    MessageBox.Show(searchResults.Count)
    If searchResults.Count > 0 Then
        Dim group As New DirectoryEntry(searchResults(0).Path)
        For Each member As Object In group.Properties("MemberOf")
            MessageBox.Show("Pre: "+ member) 'This message box returns all the groups the user is apart of.
            If group.Properties("memberOf").Contains("test-") = True Then
                MessageBox.Show(member) ' This message box never shows
            End If
        Next
    End If
    Return Groups
End Function

Is there any way of applying a search or If statement agains an Object where the constraint is a wildcard?

The groups I am looking for could be one of about 60 (this amount does increase and decrease as staff leave).

I am using VB.NET 2.0.

Thanks,

Matt

Upvotes: 3

Views: 6152

Answers (3)

Oleg
Oleg

Reputation: 221997

it seems to me that you should search for the groups where the user is the member. For example if the CN of the user which you examine is CN=Test,CN=Users,DC=mydomain,DC=local, then the corresponding LDAP query should be

(&(cn=test-*)(objectCategory=group)(member=CN=Test,CN=Users,DC=mydomain,DC=local))

As the properties which should be loaded you should choose attributes of group LDAP object.

Upvotes: 1

Zippit
Zippit

Reputation: 1683

Make sure the group you are trying to query for is a "Global Group". I had a lot of trouble getting group membership code to work. The only way it ever worked for me was if the group was a "Global Group".

Upvotes: 0

ig0774
ig0774

Reputation: 41257

LDAP search filters allow you to use * as a wildcard, so you should be able to limit the search to the users you want by changing your filter to:

(&(ObjectClass=User)(CN=" & userName & ")(memberOf=test-*))

This should be quite a bit more efficient than looping through and restricting the results in code.

It may be helpful to take a look at Microsoft's documentation on LDAP filters.

Upvotes: 1

Related Questions