How to get users from nested AD groups in SharePoint

As we know we can assign permission to specific AD groups from SharePoint workspace. So all users presents in that specific AD groups can get permission to SharePoint sites based on the permission defined to this AD groups in SharePoint sites. If this AD group is a nested AD group then also all users present in all nested groups can have the permission to this SharePoint site.

If there are requirements to list out all the users present in a specific AD group (Nested AD group) then this below mentioned code functions will help you in getting the Users presents in Nested AD groups.

[code lang=”c”]

using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Security;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;

namespace ConsoleApplicationForADGroupMembers
{
private class Program
{
static void Main(string[] args)
{
try
{
string adGroup = “AdGroup Name”;//Provide the ADGroup Name.
CheckNestedAdGroups(adGroup);
Console.ReadLine();
}
catch (Exception ex) { }
}
private static void CheckNestedAdGroups(string adgrpName)
{
try
{
using (PrincipalContext pContext = new PrincipalContext(ContextType.Domain, “Domain Name”)) //Provide the SharePoint Server Domain Name.
{
try
{
GroupPrincipal adGroup = GroupPrincipal.FindByIdentity(pContext, adgrpName); //Provide the ADGroup Name
PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> src = adGroup.GetMembers(false);// Here true or false decides whether it will be recursive or not.

foreach (System.DirectoryServices.AccountManagement.Principal item in src.ToList())
{
if (item.StructuralObjectClass.ToLower() == “user”)
{
//SharePoint User
string userloginName = string.Empty;
userloginName = item.SamAccountName;
Console.WriteLine(userloginName);
}
else
{
//AD Group
string userloginName = string.Empty;
userloginName = item.SamAccountName;
Console.WriteLine(userloginName);

CheckNestedAdGroups(userloginName);//if ADGroup it will agin call the same function to get the members within it.
}
}
}
catch (Exception ex) { }
}
}
catch (Exception ex) { }
}
}
}

[/code]

This solution is brought to you by our SharePoint professionals…

Softree Technology employs SharePoint consultants, who are experienced in writing for a multiplicity of SharePoint verticals including technical, promotional, creative, branding content, cataloging and ethical media comprising journalism.

With more than 10 years of industry experience, these professionals have the best resources to deliver optimum results. They have been satisfying customers with some of the best SharePoint Strategies.  

Tags: , , ,

1 thought on “How to get users from nested AD groups in SharePoint

Leave a Reply

Your email address will not be published. Required fields are marked *