Imports System.DirectoryServices
'This function returns a list of all security groups in the domain directory
Public Function GetSecurityGroupList(ByVal ldapPath As String, adminAccount As String, ByVal adminPwd As String) As List(Of String)
Dim grpLst As New List(Of String)
Using rootEntry As New DirectoryEntry(ldapPath, adminAccount, adminPwd)
Using searcher As New DirectorySearcher(_rootEntry)
searcher.Filter = "(&(ObjectClass=Group))"
Using results As SearchResultCollection = searcher.FindAll
For Each grp As SearchResult In results
grpLst.Add(grp.GetDirectoryEntry.Name.Substring(3))
Next
grpLst.Sort()
End Using
End Using
End Using
Return grpLst
End Function
'This function returns a datatable containing all users that are members of a given security group.
Public Function GetGroupMembers(ByVal groupName As String, ByVal ldapPath As String, adminAccount As String, ByVal adminPwd As String) As DataTable
Dim dt As New DataTable(groupName)
With dt.Columns
.Add("AccountID", GetType(String))
.Add("FirstName", GetType(String))
.Add("LastName", GetType(String))
.Add("DisplayName", GetType(String))
.Add("AccountDisabled", GetType(Boolean))
End With
Using rootEntry As New DirectoryEntry(ldapPath, adminAccount, adminPwd)
Using searcher As New DirectorySearcher(rootEntry)
If groupName.ToUpper = "DOMAIN USERS" Then
searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
Using results As SearchResultCollection = searcher.FindAll
Dim user As DirectoryEntry = Nothing
For Each result As SearchResult In results
user = result.GetDirectoryEntry
Dim props As PropertyCollection = user.Properties
dt.Rows.Add(props("sAMAccountName").Value, props("givenName").Value, props("sn").Value, props("displayName").Value, CBool(user.InvokeGet("AccountDisabled")))
Next
End Using
Else
searcher.Filter = String.Format("(&(ObjectClass=Group)(CN={0}))", groupName)
Dim result As SearchResult = searcher.FindOne
Dim members As Object = result.GetDirectoryEntry.Invoke("Members", Nothing) '<<< Get members
For Each member As Object In CType(members, IEnumerable) '<<< loop through members
Dim currentMember As New DirectoryEntry(member) '<<< Get directoryentry for user
If currentMember.SchemaClassName.ToLower = "user" Then
Dim props As PropertyCollection = currentMember.Properties
dt.Rows.Add(props("sAMAccountName").Value, props("givenName").Value, props("sn").Value, props("displayName").Value, CBool(currentMember.InvokeGet("AccountDisabled")))
End If
Next
End If
End Using
End Using
Return dt
End Function