开发者

Get members of Active Directory Group and check if they are enabled or disabled

What is the fastest way to get a list of all members/users in a given AD group and determine whether or not a user is enabled (or disabled)?

We are potentially talking about 20K users, so I would like to avoid hitting the AD for each individual use开发者_如何转开发r.


If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);

      // do whatever you need to do to those members
      UserPrincipal theUser = p as UserPrincipal;

      if(theUser != null)
      {
          if(theUser.IsAccountLockedOut()) 
          {
               ...
          }
          else
          {
               ...
          }
      }
   }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!


Please can you try the following code. it use Search Filter Syntax to get what you want in one LDAP query and recursively. The interest is that the query is done on the server. I'am not sure that it faster than @marc_s solution but it exists, and it works on framework .NET 2.0 (begining W2K3 SP2).

string sFromWhere = "LDAP://WM2008R2ENT:389/dc=dom,dc=fr";
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "test.2011");

/* To find all the users member of groups "Grp1"  :
 * Set the base to the groups container DN; for example root DN (dc=societe,dc=fr) 
 * Set the scope to subtree
 * Use the following filter :
 * (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X)
 * coupled with LDAP_MATCHING_RULE_BIT_AND on userAccountControl with ACCOUNTDISABLE
 */
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=MonGrpSec,OU=MonOu,DC=dom,DC=fr)(userAccountControl:1.2.840.113556.1.4.803:=2))";
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");

SearchResultCollection srcUsers = dsLookFor.FindAll();

/* Just to know if user is present in an other group
 */
foreach (SearchResult srcUser in srcUsers)
{
  Console.WriteLine("{0}", srcUser.Path);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜