I need to remove a user from multiple selected Active Directory groups in a ListBox (lstMemberOf.SelectedItem.Value).
Below is my code that I use to remove one group at a time for a user. This works fine. I just can't figure out how to remove more than one group at a time.
Any help would be appreciated! Thank you!!
Get Groups - Fill Listbox:
Private Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load
If Not IsPostBack Then
Sub getUserGroups()
End If
End Sub
Sub getUserGroups()
Dim result As List(Of GroupPrincipal) = New List(Of GroupPrincipal)()
Dim domainContext As PrincipalContext = New PrincipalContext(ContextType.Domain, "ldap", "username", "password")
Dim inputUser As UserPrincipal = New UserPrincipal(domainContext)
inputUser.SamAccountName = lblUN.Text.ToLower()
Dim adSearcher As PrincipalSearcher = New PrincipalSearcher(inputUser)
inputUser = CType(adSearcher.FindAll().ElementAt(0), UserPrincipal)
Dim userGroups = inputUser.GetGroups()
lstMemberOf.DataSource = userGroups
lstMemberOf.DataBind()
End Sub
Remove user from selected group:
Protected Sub btnRemoveGroup_Click(sender As Object, e As EventArgs)
RemoveUserFromGroup(lblUN.Text, lstMemberOf.SelectedItem.Text)
End Sub
Public Sub RemoveUserFromGroup(ByVal userId As String, ByVal groupName As String)
Try
Using pc As PrincipalContext = New PrincipalContext(ContextType.Domain, "ldap", "username", "password")
Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(pc, groupName)
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(pc, userId)
'group.Members.Remove(pc, IdentityType.UserPrincipalName, userId)
group.Members.Remove(user)
group.Save()
End Using
Catch E As System.DirectoryServices.DirectoryServicesCOMException
End Try
End Sub
HTML
<asp:Button ID="btnRemoveGroup" runat="server" Text="Remove" OnClick="btnRemoveGroup_Click" />
<asp:ListBox ID="lstMemberOf" runat="server" Width="100%" Rows="10" SelectionMode="Multiple"></asp:ListBox>