从 AD 获取经理的员工

Get manager's employees from AD

我正在尝试根据经理的 DN 获取他的员工列表。 假设登录用户是经理,

1) 使用 sAMAccountName(即域 ID)在活动目录中搜索管理器并检索可分辨名称

2) 在活动目录中搜索所有 "manager" 属性等于先前检索的 distinguishedName

的用户对象

但是,我的目录条目集合始终是空的。这是我所做的,假设给出了 user/manager 的 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');

运气不好。感谢任何帮助。

按照 itsme86 的建议设置包含所有用户的容器和 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;
}