1

I have the following situation:

AD:

  • Users
  • Groups

Sharepoint:

  • Groups

The hole point is to add both the users and the groups from AD to Sharepoint. I got adding the users to work using the following code:

    User adUser = ctx.Web.EnsureUser(ad.LogOnName);
    ctx.Load(adUser);
    gc.Users.AddUser(adUser);
    ctx.Load(gc, x => x.Users);

Where the LogOnName is the User Principal Name of the user. When adding the groups as LogOnName is used the group name.

Any suggestions where I am mistaken wehn adding the groups?

1

Below is my sample tested code for your reference:

User group = ctx.Web.EnsureUser("SecurityGroup");
ctx.Load(gc);
User addUser=gc.Users.AddUser(group);
ctx.Load(addUser);
ctx.ExecuteQuery();

Update:

For the Office 365 group, use the group email in the code:

User group = ctx.Web.EnsureUser("group@tenant.onmicrosoft.com");
3
  • thanks for your response. That will work for the security group but at the moment i add the Office365 group i get an exception: the collection was modified enumeration operation may not execute. I am looping trough all of my Sharepoint groups and adding users/groups dynamically.
    – JohnRambo
    Nov 23 '20 at 8:37
  • 1
    For the Office365 group, you could use the group email in the code. Nov 23 '20 at 8:54
  • Thank you! It is working perfectly!
    – JohnRambo
    Nov 23 '20 at 9:04
0

Adding an AD group to an existing SharePoint group CSOM:

           //Ensure AD group Name 
            User adGroup = clientContext.Web.EnsureUser(@"domain\ADgroupName");
            clientContext.Load(adGroup);

            GroupCollection groupColl = clientContext.Web.SiteGroups;
            Group spgroup = groupColl.GetByName("SPVisitors"); //SharePoint Existing Group
            spgroup.Users.AddUser(adGroup);
            clientContext.Load(spgroup);
            clientContext.ExecuteQuery();

1
  • thanks for your response! Just a question....where i can find the domain or it just have to say "domain\ADgroupName"
    – JohnRambo
    Nov 23 '20 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.