Trying to remove a user from multiple security groups using VB.NET

Hi
I'm trying to remove a user from multiple security groups using VB.NET. I can do it in vbs but .NET is killing me :o(
I know I have to find the user, enumerate what they have and then loop around each one removing them from the groups but I'm having no joy.
Looked around the web and can't quite put 2 and 2 together.

Would it be possible please for someone to throw together a brief bit of code that will:
1) Find one user in AD
2) List what groups they are in (if any)
3) Remove that user from those groups

I'm using Visual Studio 2008, got all my Imports ect and would appreciate this as I'm running out of time on a project.
Thanks
 Stuart
stubarAsked:
Who is Participating?
 
grayeConnect With a Mentor Commented:
Okey dokey...how's this for starters
'add a Refernce to "System.DirectoryServices"
Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim ldap As String
        Dim obj As Object
        Dim entry, grp As System.DirectoryServices.DirectoryEntry
        Dim srch As System.DirectoryServices.DirectorySearcher
        Dim result As System.DirectoryServices.SearchResult
 
        ' Step 1... open AD
        ldap = "LDAP://" & DomainName.Text
        entry = New System.DirectoryServices.DirectoryEntry(ldap)
        srch = New DirectoryServices.DirectorySearcher(entry)
 
        ' Step 2... perform the search
        srch.Filter = "(&(&(objectClass=user)(objectCategory=person))(Name=" & UserName.Text & "))"
        result = srch.FindOne()
        ' a quick sanity check
        If IsNothing(result) Then
            MsgBox("Yikes, can't find that user!")
            Exit Sub
        End If
 
        ' Step 3... get the list of groups
        For Each obj In CType(result.GetDirectoryEntry.Invoke("Groups"), System.Collections.IEnumerable)
            ' cast it back to DirectoryEntry
            grp = New System.DirectoryServices.DirectoryEntry(obj)
            Debug.WriteLine(grp.Properties("Name").Value)
 
            ' Step 4... remove the user from the group
            grp.Properties("Members").Remove(result.GetDirectoryEntry)
            grp.CommitChanges()
        Next
    End Sub
End Class

Open in new window

0
 
stubarAuthor Commented:
Apologies for the tardiness.
In the end I went with another option but as this solution fits the bill I am still awarding the points.
Thanks again.

Stuart
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.