How can I remove all users in an Active Directory group?

Posted by Beavis on Stack Overflow See other posts from Stack Overflow or by Beavis
Published on 2010-06-08T15:43:38Z Indexed on 2010/06/08 15:52 UTC
Read the original article Hit count: 152

Filed under:
|
|

I'm trying to remove all users from an AD group with the following code:

private void RemoveStudents() {
        foreach (DirectoryEntry childDir in rootRefreshDir.Children) {
            DirectoryEntry groupDE = new DirectoryEntry(childDir.Path);

            for (int counter = 0; counter < groupDE.Properties["member"].Count; counter++) {
                groupDE.Properties["member"].Remove(groupDE.Properties["member"][counter]);
                groupDE.CommitChanges();
                groupDE.Close(); 
            }             
        }      
    }    

The rootRefreshDir is the directory that contains all the AD groups (childDir).

What I'm finding here is that this code does not behave correctly. It removes users, but it doesn't do it after the first run. It does "some". Then I run it again, and again, and again - depending on how many users need to be deleted in a group. I'm not sure why it's functioning this way.

Can someone help fix this code or provide an alternative method to delete all users in a group? Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET