有没有办法让所有活跃用户分成多个小组?
例如:
获取“AdGroupA”或“AdGroupB”或“AdGroupC”
中的所有活跃用户
我看过有关单组但不是多组的帖子。
感谢。
答案 0 :(得分:2)
如果我理解正确,您只想返回多个组中的整个用户列表?这应该像从单个组中多次获取用户一样简单。
public IEnumberable<UserPrincipal> GetUsersFromGroups(string[] groupNames)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
{
foreach (var groupName in groupNames)
{
foreach (var userPrincipal in GroupPrincipal.FindByIdentity(ctx, groupName)
.GetMembers())
{
yield return userPrincipal;
}
}
}
}
以下是一种不使用AccountManagement的方法:
using System.DirectoryServices;
public static IEnumerable<DirectoryEntry> GetUsersFromGroups(string[] groupNames)
{
if (groupNames.Length > 0)
{
var searcher = new DirectorySearcher();
string searchFilter = "(&(objectClass=Group)"; //filter for groups
searchFilter += "(|"; //start a group of or parameters
foreach (var group in groupNames) //loop through the group names
{
searchFilter += string.Format("(SAMAccountName={0})",group); //add a parameter for each group in the list
}
searchFilter += "))"; //close off the filter string
searcher.Filter = searchFilter; //add the filter to the searcher
searcher.PropertiesToLoad.Add("member"); // load the members property for the group
var searchResults = searcher.FindAll(); // perform the search
foreach (SearchResult result in searchResults)
{
var directoryEntry = (DirectoryEntry)result.GetDirectoryEntry(); // get the directory entry for the group
PropertyValueCollection members = directoryEntry.Properties["member"]; // get the members collection
foreach (string name in members) //iterate through the members. this string will be the distinguished name
{
yield return new DirectoryEntry(string.Format("LDAP://{0}",name)); //return the directory entry. you may get the entry and return the display name or just return distinguished name.
}
}
}
}
在我的环境中,我发现平均比使用DirectoryServices.AccountManagement 1组快25%,但随着组和用户数量的增加,AccountManagement方法实际上变得更快。这只查询AD一次,而第一种方法每组查询一次。