Link to home
Start Free TrialLog in
Avatar of Brian
BrianFlag for United States of America

asked on

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

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!
Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

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

Open in new window

Avatar of Brian

ASKER

Okay, thanks, but I was looking to get rid of searching altogether given that we know exactly where the group is located in AD.
ASKER CERTIFIED SOLUTION
Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brian

ASKER

Awesome... thank you so much, Shaun!
Anytime ;)