Get Groups Distinguished Names
Returns a list of distinguishedNames of groups matching the provided CN filter (with or without wildcard), using LdapConnection and credentials.
VB
Public Function ldGetGroupsDistinguishedNames(cnFilter As String,
server As String,
domain As String,
username As String,
password As String) As List(Of String)
Dim results As New List(Of String)
If String.IsNullOrEmpty(cnFilter) OrElse String.IsNullOrEmpty(server) OrElse String.IsNullOrEmpty(domain) Then
Throw New ArgumentException("CN filter, server and domain must not be empty.")
End If
' Setup LDAP connection and credentials
Dim ldapCon As New LdapConnection(server)
Dim networkCreds As New NetworkCredential(username, password, domain)
ldapCon.AuthType = AuthType.Negotiate
' Bind to the LDAP server
Try
ldapCon.Bind(networkCreds)
Catch ex As Exception
Throw New ArgumentException("LDAP bind error: " & ex.Message)
Return results
End Try
' Build the LDAP query filter
Dim queryString As String = "(&(objectClass=group)(cn=" & cnFilter & "))"
' Empty array to retrieve all attributes (or specify attributes to load)
Dim emptyArray As String() = {}
' Build the search request
Dim searchRequest As New SearchRequest(domain, queryString, Protocols.SearchScope.Subtree, emptyArray)
' Issue the search request
Try
Dim searchResponse As SearchResponse = CType(ldapCon.SendRequest(searchRequest), SearchResponse)
For Each entry As SearchResultEntry In searchResponse.Entries
If entry.Attributes.Contains("distinguishedName") Then
Dim dn As String = entry.Attributes("distinguishedName")(0).ToString()
results.Add(dn)
End If
Next
Catch ex As Exception
Throw New Exception("LDAP search error: " & ex.Message & vbCrLf & "Query: " & queryString & vbCrLf)
End Try
Return results
End Function