C# Active Directory-在组中查找计算机
我试图做一个非常简单的广告查询,看看一台计算机是否在一个组中。下面的代码看起来很直观,但不起作用。LDAPString是NetBIOSName引用的计算机所属组的完全区分名称C# Active Directory-在组中查找计算机,c#,active-directory,ldap,C#,Active Directory,Ldap,我试图做一个非常简单的广告查询,看看一台计算机是否在一个组中。下面的代码看起来很直观,但不起作用。LDAPString是NetBIOSName引用的计算机所属组的完全区分名称 public bool IsComputerInADGroup(String LDAPString, String NetBIOSName) { using (DirectoryEntry entry = new DirectoryEntry(String.Format(@"LDAP://{0}", LDAPStr
public bool IsComputerInADGroup(String LDAPString, String NetBIOSName)
{
using (DirectoryEntry entry = new DirectoryEntry(String.Format(@"LDAP://{0}", LDAPString)))
using (DirectorySearcher computerSearch = new DirectorySearcher(entry))
{
ComputerSearch.Filter = String.Format("(&(objectCategory=computer)(CN={0}))", NetBIOSName);
SearchResult match = ComputerSearch.FindOne();
if (match != null)
{
return true;
}
}
return false;
}
请有人解释一下为什么这是不正确的,以及执行此搜索的正确/最快方法是什么
谢谢
P
您的基本假设是错误的-计算机(或用户)不可能在一个组中意味着“包含”在一个组中;用户或计算机仅在OU中
用户或计算机可以是任意数量组的成员,但您需要对照组的成员属性(或作为该组成员的元素的成员属性)进行检查 所以最简单的方法就是- 绑定到所讨论的对象
- 刷新其属性缓存以获取
memberOf
- 枚举其
条目,查看您要查找的组是否存在memberOf
public static bool IsAccountMemberOfGroup(string account, string group)
{
bool found = false;
using (DirectoryEntry entry = new DirectoryEntry(account))
{
entry.RefreshCache(new string[] { "memberOf" });
foreach (string memberOf in entry.Properties["memberOf"])
{
if (string.Compare(memberOf, group, true) == 0)
{
found = true;
break;
}
}
}
return found;
}
这样称呼:
bool isMemberOf =
IsAccountMemberOfGroup("LDAP://cn=YourComputer,dc=Corp,dc=com",
"CN=yourGroupInQuestion,OU=SomeOU,dc=corp,dc=com");
你应该没事的
更新:如果您使用的是.NET 3.5,还可以使用新的System.DirectoryServices.AccountManagement
命名空间和LINQ使事情变得更加简单:
public static bool IsAccountMemberOfGroup2(PrincipalContext ctx, string account, string groupName)
{
bool found = false;
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
if (group != null)
{
found = group.GetMembers()
.Any(m => string.Compare(m.DistinguishedName, account, true) == 0);
}
return found;
}
并称之为:
// establish default domain context
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
// call your function
bool isMemberOf =
IsAccountMemberOfGroup2(domain,
"cn=YourComputer,dc=Corp,dc=com",
"CN=yourGroupInQuestion,OU=SomeOU,dc=corp,dc=com");
当你说它不工作时,你的意思是你找不到电脑?如果是,首先检查计算机是否在组中,有一个很好的工具名为Active directory exporer,它可以帮助您: 如果它在组中,您可以尝试消除过滤器上计算机名的过滤器,并在结果集上迭代,以确定您的元素是否存在:
ComputerSearch.Filter = ("(&(objectCategory=computer))";
SearchResult match = ComputerSearch.FindAll();
下面是一些关于如何查询广告的信息:感谢您花时间解释。这是有道理的,也是一种享受。