I am 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();
}
}
}
rootRefreshDir is a directory containing all AD groups (childDir).
What I find here is that this code is not behaving correctly. It deletes users, but it does not do this after the first launch. These are "some." Then I start it again and again, and again - depending on how many users need to be removed in the group. I'm not sure why it works that way.
Can someone help me fix this code or provide an alternative method to delete all users in the group?
source
share