Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

removed a computer from a group

Posted on 2010-08-19
15
Medium Priority
?
534 Views
Last Modified: 2013-11-07
I have found this code and would like to modify it to remove instead of add.  It will also be a computer that will be removed from the group, not a user if that makes any differance.  How could this be modifed to work?
  '' <summary>
    ''' Method to add a user to a group
    ''' </summary>
    ''' <param name="de">DirectoryEntry to use</param>
    ''' <param name="deUser">User DirectoryEntry to use</param>
    ''' <param name="GroupName">Group Name to add user to</param>
    Public Shared Sub AddUserToGroup(ByVal de As DirectoryEntry, ByVal deUser As DirectoryEntry, ByVal GroupName As String)
        Dim deSearch As DirectorySearcher = New DirectorySearcher()
        deSearch.SearchRoot = de
        deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
        Dim results As SearchResultCollection = deSearch.FindAll()
        Dim isGroupMember As Boolean = False
        If results.Count > 0 Then
            Dim group As New DirectoryEntry(results(0).Path)
            Dim members As Object = group.Invoke("Members", Nothing)
            For Each member As Object In CType(members, IEnumerable)
                Dim x As DirectoryEntry = New DirectoryEntry(member)
                Dim name As String = x.Name
                If name <> deUser.Name Then
                    isGroupMember = False
                Else
                    isGroupMember = True
                    Exit For
                End If
            Next member
            If (Not isGroupMember) Then
                group.Invoke("Add", New Object() {deUser.Path.ToString()})
            End If
            group.Close()
        End If
        Return
    End Sub
0
Comment
Question by:chadmanvb
  • 8
  • 7
15 Comments
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33476443
to remove computer from group use the following function:u need to pass ldap path of user/gourp.this code applies to computers as well.public void RemoveUserFromGroup(string userDn, string groupDn){    try    {        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);        dirEntry.Properties["member"].Remove(userDn);        dirEntry.CommitChanges();        dirEntry.Close();    }    catch (System.DirectoryServices.DirectoryServicesCOMException E)    {        //doSomething with E.Message.ToString();    }}
0
 

Author Comment

by:chadmanvb
ID: 33478778
I tried that and I cant get it to work.  Is this correct:
Public Sub RemoveUserFromGroup(userDn As String, groupDn As String)
        Try
            Dim dirEntry As New DirectoryEntry("LDAP://" & groupDn)
            dirEntry.Properties("memberOf").Remove("LDAP://" & userDn)    'tried without ldap:// also
            dirEntry.CommitChanges()
            dirEntry.Close()

            'doSomething with E.Message.ToString()
        Catch E As System.DirectoryServices.DirectoryServicesCOMException



        End Try
    End Sub
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33478840
both userDn and  groupDn should be with passed to function with no LDAP prefix.
and no need to change function code, it should work.

>>userDn As String, groupDn

exception is thrown or the object was not removed?
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33478975
>>I tried that and I cant get it to work.  

the computer was not removed from the group, or an exception was thrown?
0
 

Author Comment

by:chadmanvb
ID: 33481694
I get an error telling me

The server is unwilling to process the request. (Exception from HRESULT: 0x80072035)

However I have simlar code that does work.  The code below works fine for me:
 Public Sub AddAttribute(ByVal LdapString As String, ByVal pName As String, ByVal pValue As String)

        Using dir As New DirectoryEntry(LdapString)

            Try
                dir.Properties(pName).Add(pValue)
                dir.CommitChanges()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

        End Using

    End Sub
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33491095
which line triggers the exception?
0
 

Author Comment

by:chadmanvb
ID: 33491405
It fails on:

 dirEntry.CommitChanges()
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33492458
i think this is permissions issue.
you need to delegate the task Modify the membership of a group.
check http://social.technet.microsoft.com/Forums/en-US/winserverDS/thread/60f7317b-c356-4c89-8225-e8123ef15777
0
 

Author Comment

by:chadmanvb
ID: 33492917
The application is being run as a domain admin.  I can make the changes fine via user and computers snapin.  Can it still be permissions?
0
 

Author Comment

by:chadmanvb
ID: 33493647
another note.  I can run this with vbscript and remove computer from a group.  It would just make it easier to do this within my .net application.

       Set objGroup = GetObject("LDAP://" & mid(strData,12))      'skip "memberOf : " that is in front of link
                        objGroup.Remove ("LDAP://" & strLocation)      'remove from group
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33494120
i actually tried it using vbs as well, and it worked.
i google for this error and they all pointed out to be a permission issue.
i'll keep looking for a solution...
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33494395
can u make sure that u pass userDn and groupDn  without "LDAP:\\" prefix?
that should work, i've dbl checked it.

Public Sub RemoveUserFromGroup(userDn As String, groupDn As String)
        Try
            Dim dirEntry As New DirectoryEntry("LDAP://" & groupDn)
            dirEntry.Properties("memberOf").Remove(userDn)
            dirEntry.CommitChanges()
            dirEntry.Close()

            'doSomething with E.Message.ToString()
        Catch E As System.DirectoryServices.DirectoryServicesCOMException



        End Try
    End Sub
0
 

Author Comment

by:chadmanvb
ID: 33495280
Here is what I have.  I just created a group and added myself to it.  i still get the same error.  Do you see anything I might have wrong?

Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click

        Dim deUser As String = "CN=myuserid,OU=Home Office,OU=US,OU=People,DC=mydomian,DC=com"

        Dim groupDn As String = "CN=chadtest,OU=Groups,DC=mydomain,DC=com"


        RemoveUserFromGroup(deUser, groupDn)
    End Sub






    Public Sub RemoveUserFromGroup(ByVal userDn As String, ByVal groupDn As String)
        Try
            Dim dirEntry As New DirectoryEntry("LDAP://" & groupDn)
            dirEntry.Properties("memberOf").Remove(userDn)
            dirEntry.CommitChanges()
            dirEntry.Close()

            'doSomething with E.Message.ToString()
        Catch E As System.DirectoryServices.DirectoryServicesCOMException
            MsgBox(E.Message)
        End Try
    End Sub
0
 
LVL 42

Accepted Solution

by:
Meir Rivkin earned 2000 total points
ID: 33495323
try this:
Private Shared Sub RemoveUserFromGroup(userDn As String, groupDn As String)
	Dim proc As Process = Process.Start("dsmod", String.Format("group ""{0}"" -rmmbr ""{1}""", groupDn, userDn))
	proc.WaitForExit()
	If proc.ExitCode <> 0 Then
		Console.WriteLine("Could not remove user {0} from group {1}", userDn, groupDn)
	End If
End Sub

Open in new window

0
 

Author Closing Comment

by:chadmanvb
ID: 33495411
That did it!  Thanks so much for all of the help!  Do you mind looking at another questions I just posted.  Just need to have it add to a group.  Also want to know if I can run this from a loop that contains 20 calls to that function.  I posted it at
http://www.experts-exchange.com/Programming/Languages/.NET/Q_26420616.html
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question