如何检索给定AD组中的用户?
我是否首先使用域,用户名和密码实例化PrincipalContext?
答案 0 :(得分:14)
首先,找到该组。然后使用GetMembers()枚举其用户。
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var group = GroupPrincipal.FindByIdentity( context, "groupname" ))
{
var users = group.GetMembers( true ); // recursively enumerate
...
}
}
请注意,在.NET 4.0中修复了一个错误,它将无法枚举超过1500个组成员。如果您有一个大型组,则需要使用alternative method利用System.DirectoryServices中的旧方法。
答案 1 :(得分:4)
查看本文Managing Directory Security Principals in the .NET Framework 3.5,详细了解如何使用.NET 3.5中的System.DirectoryServices.AccountManagement
。
至于检索组的成员,请执行以下操作:
// build the principal context - use the NetBIOS domain name
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAIN");
// get the group you're interested in
GroupPrincipal group = GroupPrincipal.FindByIdentity("cn=YourGroupname");
// iterate over its members
foreach(Principal p in group.Members)
{
// do whatever you need to do to its members here
}
希望这有帮助!
答案 2 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices.AccountManagement;
namespace ExportActiveDirectoryGroupsUsers
{
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null, useage: ExportActiveDirectoryGroupsUsers OutputPath"); // Check for null array
}
else
{
Console.Write("args length is ");
Console.WriteLine(args.Length); // Write array length
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Console.Write("args index ");
Console.Write(i); // Write index
Console.Write(" is [");
Console.Write(argument); // Write string
Console.WriteLine("]");
}
try
{
using (var ServerContext = new PrincipalContext(ContextType.Domain, ServerAddress, Username, Password))
{
/// define a "query-by-example" principal - here, we search for a GroupPrincipal
GroupPrincipal qbeGroup = new GroupPrincipal(ServerContext, args[0]);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
// find all matches
foreach (var found in srch.FindAll())
{
GroupPrincipal foundGroup = found as GroupPrincipal;
if (foundGroup != null)
{
// iterate over members
foreach (Principal p in foundGroup.GetMembers())
{
Console.WriteLine("{0}|{1}", foundGroup.Name, p.DisplayName);
// do whatever you need to do to those members
}
}
}
}
//Console.WriteLine("end");
}
catch (Exception ex)
{
Console.WriteLine("Something wrong happened in the AD Query module: " + ex.ToString());
}
Console.ReadLine();
}
}
}
}