2

I've been tasked with creating a solution to add and remove AD users to and from AD groups. The following code is functional, except when I try to save the group. I'm getting an exception of "The object already exists." I've narrowed down the issue (I think) to the SamAccountName, and I think that is what is causing the exception.

I don't have access to modify anything in AD aside from the permissions I've been granted to modify the groups designated to have users added/removed from them. I've done endless research, and I just haven't been able to determine a solution. Any help would be deeply appreciated. Thanks in advance.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "address", "DN", "username", "password");
GroupPrincipal grp = new GroupPrincipal(ctx, sGroup);
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, sUser);
if (grp != null)
{                  
    grp.Members.Add(usr);
    grp.Save();
}
JoelC
  • 3,664
  • 9
  • 33
  • 38
Aaron
  • 23
  • 1
  • 4

1 Answers1

2

It appears to me that you are creating a new group with the same name as an existing one. Instead of

GroupPrincipal grp = new GroupPrincipal(ctx, sGroup);

could you try

GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, sGroup);

to get the existing group and then modify that?

lordjeb
  • 1,286
  • 9
  • 14
  • I modified the code to match as shown above, I'm getting back the exception "Multiple principals contain a matching Identity." – Aaron Sep 23 '14 at 21:29
  • 1
    You may need to be more accurate in providing sGroup: `GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, sGroup);`. Or provide a distinguished name. Basically you have two objects that AD thinks match whatever you're passing there. – lordjeb Sep 23 '14 at 21:33
  • ***IsMemberOf*** `var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userId.ToLower()); var group = GroupPrincipal.FindByIdentity(pc, groupName); if (group == null || user == null) return false; return user.IsMemberOf(group);` – Kiquenet Jul 07 '22 at 07:56