在为用户查询Active Directory时 – 有没有办法过滤掉为计算机创建的用户帐户?理想情况下,这种方式在大多数典型网络中都很常见.例如.:
- DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry([Users_OU_root]));
- ds.filter = "(&(objectClass=User)([CRITERIA_TO_FILTER_OUT_COMPUTER_USER_ACCOUNTS]))";
- ds.FindAll();
- ...
解决方法
如果您使用的是.NET 3.5及更高版本,则应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间.在这里阅读所有相关内容:
> Managing Directory Security Principals in the .NET Framework 3.5
> MSDN docs on System.DirectoryServices.AccountManagement
基本上,您可以定义域上下文并轻松查找AD中的用户和/或组:
- // set up domain context
- PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
- // find a user
- UserPrincipal user = UserPrincipal.FindByIdentity(ctx,"SomeUserName");
- if(user != null)
- {
- // do something here....
- }
- // find the group in question
- GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx,"YourGroupNameHere");
- // if found....
- if (group != null)
- {
- // iterate over members
- foreach (Principal p in group.GetMembers())
- {
- Console.WriteLine("{0}: {1}",p.StructuralObjectClass,p.DisplayName);
- // do whatever you need to do to those members
- }
- }
新的S.DS.AM使得在AD中使用用户和群组变得非常容易:
计算机帐户将显示为ComputerPrincipal(源自Principal) – 因此您可以轻松地将用户和计算机帐户分开.
如果您不能或不想转移到S.DS.AM – 您还可以通过在LDAP过滤器中使用objectCategory而不是objectClass来保持用户和计算机的区别. objectCategory无论如何都是有益的,因为它是索引的,而不是多值的 – 所以查询性能会好得多.
对于真实用户,请使用objectCategory = Person,而对于计算机,请在LDAP过滤器中使用objectCategory = Computer.