我正在尝试打印我公司AD中仅某些OU的用户 到目前为止,我已经想出了这个:
string groupName = "Domain Users";
string domainName = "domain";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(false))
{
Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);
}
grp.Dispose();
ctx.Dispose();
Console.ReadLine();
}
else
{
Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
Console.ReadLine();
}
问题在于它打印的每个用户而不是特定的OU,如"员工"或"学生"。
如何添加一个参数来指定它应循环而不是组的1或2个OU?
答案 0 :(得分:0)
我完全不知道你的代码所以这是伪代码。
当你有一些财产,例如用于指定类型的字符串然后使用IdentifierAccessor
:
Where
或者它是某种继承,然后可以使用 var groupName = "Student";
foreach (Principal p in grp.GetMembers(false).Where(princ => princ.OUName.Equals(groupName))
{
Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);
}
:
OfType
答案 1 :(得分:0)
您正在搜索整个域,而“域用户”可能不是您不想要的OU,更改变量的名称并添加:
string domainName = "Domain Users";
string groupName = "Students";
然后将OU添加到PrincipalContext:
var ctx = new PrincipalContext(ContextType.Domain, domainName, groupName);
答案 2 :(得分:0)
我在我的应用程序中使用以下代码。
这对你来说可能有点矫枉过正,但我认为它主要适合你的需要。
public static void DoStuff(UserPrincipal princ) {
var allDomains = Forest.GetCurrentForest().Domains.Cast<Domain>();
var allSearcher = allDomains.Select(domain => {
var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domain.Name));
searcher.Filter = $"(&(&(objectCategory=person)(objectClass=user)(userPrincipalName=*{princ.SamAccountName}*)))";
return searcher;
});
var directoryEntriesFound =
allSearcher.SelectMany(searcher =>
searcher.FindAll()
.Cast<SearchResult>()
.Select(result => result.GetDirectoryEntry()));
var memberOf = directoryEntriesFound.Select(entry => {
using (entry) {
return new {
Name = entry.Name,
GroupName = ((object[])entry.Properties["MemberOf"].Value)
.Select(obj => obj.ToString())
};
}
}
);
var result1 = new List<string>();
foreach (var member in memberOf) {
if(member.GroupName.Contains("Student") )
Console.WriteLine(princ.SamAccountName + " is Student");
if (member.GroupName.Contains("Employee"))
Console.WriteLine(princ.SamAccountName + " is Employee");
}
}
只需在foreach (Principal p in grp.GetMembers(false))
答案 3 :(得分:0)
如果要将搜索限制为单个OU /容器,可以使用另一个PrincipalContext
构造函数绑定:
string groupName = "Domain Users";
string domainName = "domain";
string ouName = "CN=Users,DC=yourcompany,DC=com";
// bind to the specified container you want
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName, ouName);
然后,当然,您仅在CN=Users
容器中搜索 - 没有其他地方。