获取活动目录组的成员并检查它们是否已启用或禁用

本文关键字:是否 启用 检查 活动 成员 获取 | 更新日期: 2023-09-27 18:06:56

获取给定AD组中所有成员/用户的列表并确定用户是否启用(或禁用)的最快方法是什么?

我们可能谈论的是20K用户,所以我希望避免为每个用户点击广告。

获取活动目录组的成员并检查它们是否已启用或禁用

如果你使用的是。net 3.5及以上版本,你应该检查一下System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。阅读这里的所有内容:

    管理。net Framework 3.5中的目录安全主体
  • System.DirectoryServices.AccountManagement上的MSDN文档

基本上,您可以定义域上下文并轻松地在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
          {
               ...
          }
      }
   }
}

新的S.DS.AM使在AD中与用户和组进行交互变得非常容易!

请尝试下面的代码。它使用搜索过滤器语法在一个LDAP查询和递归中获得您想要的内容。有趣的是,查询是在服务器上完成的。我不确定它是否比@marc_s的解决方案更快,但它确实存在,而且它可以在。net 2.0框架上工作(从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);
}