获取给定AD组中所有成员/用户列表并确定用户是否已启用(或禁用)的最快方法是什么?
我们可能会谈论20K用户,因此我希望避免为每个用户点击AD。
答案 0 :(得分:46)
如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有相关内容:
基本上,您可以定义域上下文并轻松在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中的用户和群组一起玩!
答案 1 :(得分:3)
请试试以下代码。它使用Search Filter Syntax在一个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);
}