Reputation: 2922
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?
Upvotes: 4
Views: 4531
Reputation: 151
Or if you are using
DirectoryServices.AccountManagement.GroupPrincipal
(.NET 3.5+):
This will work as well:
groupPrincipal.Members.Clear();
groupPrincipal.Save();
Upvotes: 4
Reputation: 15794
This reference in CodeProject should help:
"How To Do (almost) Everything in AD: http://www.codeproject.com/KB/system/everythingInAD.aspx
Upvotes: 0
Reputation: 34218
Your problem is that you're counting upwards... You first remove an item at index 0. Every remaining item then moves to index - 1
in the list. You then remove at index 1, and every remaining item shuffles except for the one you've now left at index 0. Basically: you're only removing half of the items.
Instead of a for
loop, try while (groupDE.Properties["member"].Count > 0)
, and simply remove the item at index 0
each time.
Upvotes: 4
Reputation: 888195
You're looping through the items as you delete them causing the index to skip every other item.
You need to change the inner for
loop to loop backwards, like this:
PropertyValueCollection members = groupDE.Properties["member"];
for (int counter = members.Count - 1; counter >= 0; counter--) {
members.RemoveAt(counter);
groupDE.CommitChanges();
groupDE.Close();
}
Upvotes: 5