How do I add a computer to a group with VB.net using LDAP credentials

Brian
Brian used Ask the Experts™
on
I have this code that works for joining a computer to a group, but occasionally fails to join. This does a search for the group, but I don't need to search, I know the exact name of the group and where it's located.  The user is adding the computer into the domain and then into groups using ldap credentials. This code searches for the group, but I have the name and location of the group so I want to avoid searching.


    Private Sub ComputerGroupAdd(ByVal GroupName As String, ByVal ComputerName As String)
        Try
            Dim sDomainName As String = "LDAP://mydomain.local"
            Dim adUserFolder As DirectoryEntry = New DirectoryEntry("LDAP://mydomain.local/DC=mydomain,DC=local")

            adUserFolder.Username = "mydomain.local\myUser"
            adUserFolder.Password = "mypassword"
            Dim adSearch As New System.DirectoryServices.DirectorySearcher(adUserFolder)

            adSearch.Filter = String.Format("(&(objectCategory=group)(sAMAccountName= {0}))", GroupName)

            For Each x As SearchResult In adSearch.FindAll
                Dim group As DirectoryEntry = x.GetDirectoryEntry
                group.Properties("member").Add(ComputerName)
                group.CommitChanges()
            Next
        Catch ex As Exception
                MsgBox(ex.Message)
        End Try
    End Sub

Open in new window

How can I add a computer to a group with credentials using the group's exact name and location. In other words, without searching for the group, which is what this code is doing. Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Shaun VermaakTechnical Specialist
Awarded 2017
Distinguished Expert 2018

Commented:
A quick fix is to change the searcher to use distinguishedName
adSearch.Filter = String.Format("(&(objectCategory=group)(distinguishedName= {0}))", GroupND)

Open in new window

Author

Commented:
Okay, thanks, but I was looking to get rid of searching altogether given that we know exactly where the group is located in AD.
Technical Specialist
Awarded 2017
Distinguished Expert 2018
Commented:
Directory Entry accepts username and password
Dim adGroup As DirectoryEntry = New DirectoryEntry(groupDN)

Open in new window


Snippet of how I use it in my C# DLL
AD.png

Author

Commented:
Awesome... thank you so much, Shaun!
Shaun VermaakTechnical Specialist
Awarded 2017
Distinguished Expert 2018

Commented:
Anytime ;)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial