How to add AD group to SharePoint 2010 SPGroup programmatically?

11.1k Views Asked by At

Been trying to add an AD group to an SPGroup programmatically and it's not working.

I've tried:

SPGroup.AddUsers("myADgroup");

and

SPGroupCollection.Add(groupName, currentUser, "myADgroup", groupDescription);

I've tried it both with domain and without.

Any ideas?

4

There are 4 best solutions below

0
On

This is a follow up from Andy Burn's answer:

From PowerShell I initially tried the following:

$web = Get-SPWeb http://localhost
$web.EnsureUser("domain\test group")

This didn't work, which was puzzling.

Some more experimentation and I found the following did work (Power Users is a built in group):

$web.EnsureUser("builtin\power users")
$web.EnsureUser("power users")
$web.EnsureUser("test group")

I then noticed that I had a different value for the Name (aliased as DisplayName in PowerShell) -- it turns out that I had used different values in Active Directory for 'Group name' and 'Group name (pre-Windows 2000)'.

The group name worked by itself, but with the domain prefix I needed to use the pre-Windows 2000 name.

With this, I was able to get the following to work:

$web.EnsureUser("domain\pre2000 test group")

So, if you are still having issues check for consistency between the two group names in AD.

2
On

Erm, there is no SPGroup.AddUsers("myAdGroup") method. There isn't even an AddUser() method with that format.

Have you tried:

SPGroup g = web.AssociatedMemberGroup;
SPUser u = web.EnsureUser("DOMAIN\\myADgroup");
g.AddUser(u);

The EnsureUser bit makes sure that the AD group is added as a user of the SPWeb, so you can then assign rights.

0
On

I also experienced a problem with calling SPWeb.EnsureUser with an AD group. In my case there was some confusion because the group in question had a display name that was different to its underlying sAMAccountName. Calling EnsureUser with the sAMAccountName rather than the display name sorted the problem for me.

0
On

Hi there is no methods for now to add AD group.

You need to create group first, aand after that add users to that group.

using (SPSite spSite = new SPSite("http://localhost"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {

        SPGroupCollection spGrps = spWeb.SiteGroups;
        SPUser uGrpOwner = spWeb.CurrentUser;
        SPUser uGrpDefMember = spWeb.CurrentUser;
        string sGrpName = "GrupeName";
        spGrps.Add(sGrpName, uGrpOwner, uGrpDefMember, "Decription");

        SPGroup spGrp = spGrps[sGrpName];

        List<SPUser> spUsersFromAD = YouFunctionGetUserFromAD(); 

        foreach(SPUser spUser  in  spUsersFromAD){
            spGrp.AddUser(spUser);
        }
        spWeb.Update();
    }
}