在Active Directory中,如何查找秘书所有的所有组?

时间:2015-04-21 15:48:19

标签: c# active-directory

我们使用Active Directory的secretary属性,这是一个多值DN属性。我想有效地查找给定用户列出的所有组secretary。在C#/ .NET中执行此查询的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

此代码将返回context个OU中包含distinguishedName作为列出的秘书之一的群组的sAMAccountNames列表:

var filter = "(&(objectClass=group)(secretary=" + distinguishedName + "))";

PrincipalContext context = new PrincipalContext(...); // place to search from
var up = new GroupPrincipal(context);
var list = new List<string>();
using (var searcher = new PrincipalSearcher(up))
{
    var ds = searcher.GetUnderlyingSearcher() as DirectorySearcher;

    // if you only want to search in a single OU (as defined by 'context')
    ds.SearchScope = SearchScope.OneLevel; 
    ds.Filter = filter;
    ds.PropertiesToLoad.Add("sAMAccountName");

    var results = ds.FindAll();
    foreach (SearchResult r in results)
    {
        var name = r.GetDirectoryEntry().Properties["sAMAccountName"].Value as string;
        list.Add(name);
    }
}