1

Help I am trying to remove domain users from local groups and every time I try to get the local groups for a domain user the collection is empty. How can I remove a domain user from any local groups on my machine. Below is the code I am using and it works fine for local users, but as stated above on domain users it says they have no local groups. I know for a fact that the domain user is in the Users and IIS_USRS groups on the local machine.

using (PrincipalContext localContext = new PrincipalContext(ContextType.Machine))
            {
                try
                {
                    foreach (GroupPrincipal principal in user.GetGroups(localContext))
                    {
                        principal.Members.Remove(user);
                        principal.Save(localContext);
                        principal.Dispose();
                    }
                }
twreid
  • 1,453
  • 2
  • 22
  • 42
  • If using .Net framework 3+, see [this question](http://stackoverflow.com/questions/2143052/adding-and-removing-users-from-active-directory-groups-in-net) – Gabriel GM Dec 10 '12 at 16:01

1 Answers1

0

In order to get this to work I ended up having to do.

using (PrincipalContext localContext = new PrincipalContext(ContextType.Machine))
            {
                try
                {
                    foreach (string g in groups)
                    {
                        using (GroupPrincipal localGroup = GroupPrincipal.FindByIdentity(localContext, IdentityType.Name, g))
                        {
                            foreach (Principal groupUser in localGroup.GetMembers().Where(groupUser => user.Name.Equals(groupUser.Name)))
                            {
                                localGroup.Members.Remove(groupUser);
                                localGroup.Save();
                            }
                        }
                    }
                }
twreid
  • 1,453
  • 2
  • 22
  • 42