Solved

removed a computer from a group

Posted on 2010-08-19
15
518 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:sedgwick
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:sedgwick
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
 
LVL 42

Expert Comment

by:sedgwick
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:sedgwick
ID: 33491095
which line triggers the exception?
0
 

Author Comment

by:chadmanvb
ID: 33491405
It fails on:

 dirEntry.CommitChanges()
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 42

Expert Comment

by:sedgwick
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:sedgwick
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:sedgwick
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:
sedgwick earned 500 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now