从广告中获取经理的员工

时间:2018-07-30 21:31:57

标签: c# active-directory distinguishedname

我正在尝试获取给定DN的经理的雇员列表。 假设登录用户是管理员,

1)使用sAMAccountName(即域ID)在活动目录中搜索管理器,并检索distinguishedName

2)搜索活动目录中具有“ manager”属性等于先前检索到的distinguishedName的所有用户对象

但是,我的目录条目集合始终为空。假设给出了用户/经理的DN,这就是我所做的。

private static List<DirectoryEntry> GetUserDEByManagerDN(string sDN)
{
    string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();
    DirectoryEntry de = new DirectoryEntry(adPath + "/" + sDN);
    List<DirectoryEntry> lsUsers = new List<DirectoryEntry>();

    using (DirectorySearcher Search = new DirectorySearcher())
    {
        Search.SearchRoot = de;
        Search.Filter = "(&(manager=" + sDN + "))";
        //Search.Filter = "(&(manager=" + sDN + ")(extensionAttribute14=INV))";
        Search.SearchScope = SearchScope.Base;  // Also tried SearchScope.Subtree
        SearchResultCollection Results = Search.FindAll();

        if (null != Results)  // Results is not null but has zero length
        {
            foreach (SearchResult Result in Results)
            {
                DirectoryEntry deUser = Result.GetDirectoryEntry();

                if (null != deUser)
                    lsUsers.Add(deUser);
            }
        }
    }
    return lsUsers;
}

我还尝试使用以下方法转义DN:

string sEscapedDN = sDN.Replace('\\', '\x5C').Replace(')', '\x29').Replace('(', '\x28').Replace('*', '\x2A');

没有运气。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

遵循其meme86的建议来设置具有所有用户的容器,以及Camilo Terevinto的具体建议从AD路径中删除管理员的DN,此问题已解决。我还不得不将搜索范围从基本树更改为子树。

以下是对我有用的东西:

private static List<DirectoryEntry> GetUserDEByManagerDN(string sManagerDN)
{
    string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();

    /* This was one of the issues  */
    //DirectoryEntry de = new DirectoryEntry(adPath + "/" + sManagerDN);
    DirectoryEntry de = new DirectoryEntry(adPath);

    List<DirectoryEntry> lsUsers = new List<DirectoryEntry>();

    using (DirectorySearcher Search = new DirectorySearcher())
    {
        Search.SearchRoot = de;

        /* I had to include extension attribute 14 to get rid of some unusual "users", like Fax, special accounts, etc. You might not need it
        //Search.Filter = "(manager=" + sDN + ")";
        Search.Filter = "(&(manager=" + sDN + ")(extensionAttribute14=INV))";

        //Search.SearchScope = SearchScope.Base;  
        Search.SearchScope = SearchScope.Subtree;
        SearchResultCollection Results = Search.FindAll();

        if (null != Results)
        {
            foreach (SearchResult Result in Results)
            {
                DirectoryEntry deUser = Result.GetDirectoryEntry();

                if (null != deUser)
                    lsUsers.Add(deUser);
            }
        }
    }
    return lsUsers;
}