Active Directory-获取多个广告组中的所有用户
本文关键字:用户 获取 Directory- Active | 更新日期: 2023-09-27 18:25:19
有没有办法让多个组中的所有活动用户?
例如:
获取"AdGroupA"、"AdGroupB"或"AdGroupC"中的所有活动用户
我看到过关于单组的帖子,但没有看到多组的帖子。
谢谢。
如果我理解正确,您只想返回多个组中的整个用户列表吗?这应该和多次从单个组中获取用户一样容易。
public IEnumerable<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 over 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.
}
}
}
}
在我的环境中,我发现这比1组使用DirectoryServices.AccountManagement
平均快25%,但随着组和用户数量的增加,AccountManagement
方法实际上变得更快了。这只查询AD一次,而第一个方法每个组查询一次。