Sub CollectGroupMemberShip()
'Reset the form to default values
ResetToDefault()
Dim strGroupList = Nothing
'Variable that will be used to cancel the rest of the process in case wrong username
UserNotFound = 0
'Various Dim to connect to AD using wished domain and user account
Dim rootDSE As New DirectoryEntry("LDAP://MyDomain/RootDSE")
Dim filterString As String = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" & UserLoginID_TextBox.Text & "))"
Dim domainRoot As New DirectoryEntry("LDAP://MyDomain/" & rootDSE.Properties("defaultNamingContext")(0).ToString())
Dim domainSearch As New DirectorySearcher(domainRoot, filterString)
'Property to search for
domainSearch.PropertiesToLoad.Add("memberOf")
Dim domainSearchResult As SearchResult = domainSearch.FindOne()
'In case the username is not found, raise an error and quit
If domainSearchResult Is Nothing Then
MsgBox("User not found. Please check the spelling!", MsgBoxStyle.Critical, "User not found...")
UserNotFound = 1
Exit Sub
End If
'For each group the user is member of, I isolate the name of the group and I add it into a list
For Each domainGroup In domainSearchResult.Properties("memberof")
'Split the full path using 'comma'
Dim Split1 = Split(domainGroup, ",")
'Split the first occurance using 'equal' to get rid of 'CN='
Dim Split2 = Split(Split1(0), "=")
'Dim the group name (OK not really necessary, but nicer for using it afterwards)
Dim GroupName = Split2(1)
'Now time to use the group list
If strGroupList = "" Then
strGroupList = GroupName
Else
strGroupList = strGroupList & "," & GroupName
End If
Next
'Split the group list using 'comma'
Dim arrGroupList = Split(strGroupList, ",")
'Using 'QuickSort' function to sort the list by alphabetical order
Quicksort(arrGroupList, LBound(arrGroupList), UBound(arrGroupList))
'Re-arrange the list to have one group per line
Dim strSortedGroups = Join(arrGroupList, vbCrLf)
'Display the result in the textbox on the form
UserGroups_TextBox.Text = strSortedGroups
'Just display on the form the number of groups the user is member of
Groups_GroupBox.Text = Groups_GroupBox.Text & " (" & arrGroupList.Length & ")"
End Sub