Fantassy
Fantassy

Reputation: 11

Remove a single user from all groups excepts domain users with c#?

I am experimenting with c# and ADDS a little bit however I am trying to remove a single user from all groups with the exception of the group Domain Users.

I know how to remove the user from a single pre-determined group using

 DirectoryEntry grprem = new DirectoryEntry(groupdn);
                grprem.invoke("remove", new object[] { userdn });
                grprem.commitchanges();
                grprem.close();

And a single user from all groups using :

user.Properties["memberof"].clear();

(Getting error with this one, I think this is due to having to leave a single primary group hence the question) But how do I leave a single group "domain users" and remove all the others?

Upvotes: 1

Views: 346

Answers (1)

Max Xapi
Max Xapi

Reputation: 815

memberOf is a special attribute computed by the directory (ie. after a new user's DN is added in a group object with the member attribute, the user's memberOf attribute values are recomputed) : so you can't add/remove/update values in it. Thus, with your existing code, the simpliest way to achieve what you need is to loop on all your user's groups and to remove your user's DN from each of this group (excepted the reserved one):

DirectoryEntry currentGroup = null;
if (user.Properties["memberOf"].Count > 0) {
    foreach (string groupDn in user.Properties["memberOf"]) {
        if (!groupDn.Equals("yourDomainUsersGroup", StringComparison.OrdinalIgnoreCase)) {
            currentGroup = new DirectoryEntry(groupDn);
            // I can't test right now, but perhaps you may not be allowed to remove a group member while looping on the memberOf attribute values
            // So you would have to use a temp list to store the groups DN and after that to do a new loop on the list and then really remove the group member
            currentGroup.Invoke("remove", new object[] { "yourUserDn" });
            currentGroup.CommitChanges();
            currentGroup.Close();
        }
    }

Upvotes: 2

Related Questions