Active Directory查询以比我的尝试更好地缩小结果范围

时间:2015-01-14 19:52:50

标签: c# active-directory adsi

我的具体问题:如何缩小我对没有设置employeeNumber属性的活动目录帐户的搜索范围(不为空或空)?

我的工作是检查结果并检查employeeNumber并删除这些帐户。但是,在我必须手动过滤之前,我希望我的查询缩小结果范围。

我认为这条线甚至没有触发过滤器:((DirectorySearcher)ps.GetUnderlyingSearcher()).Filter = "(&(objectCategory=Person)(objectClass=User)(!employeeNumber=*))";// I would like for it to return only Ad Accounts that have an employeeNumber set

 PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "myDomain");
                UserPrincipal user = new UserPrincipal(domainContext);
                user.SamAccountName = ParamSamAccountName;
                user.Enabled = true;//only enabled users
                user.PasswordNeverExpires = false; //this should get rid of service accounts

                PrincipalSearcher pS = new PrincipalSearcher();
                pS.QueryFilter = user;

                PrincipalSearcher ps = new PrincipalSearcher(user);
                ((DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 500;
               ((DirectorySearcher)ps.GetUnderlyingSearcher()).Filter = "(&(objectCategory=Person)(objectClass=User)(!(employeeNumber=*)))";//this doesnt seem to be working... bug...
                var searchResults = SafeFindAll(ps);



      private static IEnumerable<Principal> SafeFindAll(PrincipalSearcher searcher)
            {
                using (var results = searcher.FindAll())
                {
                    foreach (var result in results)
                    {
                        yield return result;
                    }
                } // SearchResultCollection will be disposed here
            }

3 个答案:

答案 0 :(得分:3)

这是我的方法:

1.Subclass UserPrincipal引入noEmployeeNumber和objectCategory属性(here是非常好的例子,对我帮助很大):

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx : UserPrincipal
{
    // Implement the constructor using the base class constructor. 
    public UserPrincipalEx(PrincipalContext context) : base(context) { }

    // Implement the constructor with initialization parameters.    
    public UserPrincipalEx(PrincipalContext context,
                         string samAccountName,
                         string password,
                         bool enabled)
        : base(context, samAccountName, password, enabled)
    { }

    // Create the "employeeNumber" property.    
    [DirectoryProperty("!employeeNumber")]
    public bool noEmployeeNumber
    {
        get
        {
            if (ExtensionGet("!employeeNumber").Length != 1) return false;
            string empNum = (string)ExtensionGet("!employeeNumber")[0];
            if (empNum == "*") return true; else return false;
        }
        set 
        {
            ExtensionSet("!employeeNumber", "*"); 
        }
    }
    // Create the "objectCategory" property.    
    [DirectoryProperty("objectCategory")]
    public string objectCategory
    {
        get
        {
            object[] result = this.ExtensionGet("objectCategory");
            if (result != null)
            {
                return (string)result[0];
            }
            else
            {
                return string.Empty;
            }
        }
        set { this.ExtensionSet("objectCategory", value); }
    }

    // Implement the overloaded search method FindByIdentity.
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue);
    }

    // Implement the overloaded search method FindByIdentity. 
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue);
    }
}

2.更改代码以使用新的UserPrincipalEx并将值分配给它的新属性:

PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "mydomain");
UserPrincipalEx user = new UserPrincipalEx(domainContext);

// here are our new properties:
user.noEmployeeNumber = true;
user.objectCategory = "person";

user.Enabled = true; //only enabled users
user.PasswordNeverExpires = false; //this should get rid of service accounts
PrincipalSearcher ps = new PrincipalSearcher(user);
var searchResults = ps.FindAll();                 

结果将是没有设置employeeNumber属性的所有用户的列表。

答案 1 :(得分:1)

你的问题有点令人困惑。如果你想要WITHOUT employeeNumber设置,那么你是正确的,如果你想要WITH employeeNumber设置然后你需要这个:(&amp;(objectCategory = Person)(objectClass = User)(employeeNumber = *))

此外,您需要确保获得LDAP连接。下面的一些代码可能会有所帮助,另请参阅此博客: http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#20

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LDAPCSharp
{

    using System.DirectoryServices;
    using System.DirectoryServices.ActiveDirectory;

    class Program
    {
        static void Main(string[] args)
        {
            var ldapDomain = FriendlyDomainToLdapDomain("domainRemoved");


            var allResults = FindAllWithEmployeeNumber(ldapDomain);

            foreach (var searchResult in allResults)
            {
                using (var entry = searchResult.GetDirectoryEntry())
                {
                    foreach (var value in entry.Properties.PropertyNames)
                    {
                        Console.WriteLine(value);
                    }
                }
            }
        }

        /// <summary>
        /// The find all.
        /// </summary>
        /// <param name="ldapDomain">
        /// The ldap domain.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable"/>.
        /// </returns>
        public static IEnumerable<SearchResult> FindAllWithEmployeeNumber(string ldapDomain)
        {
            string connectionPrefix = "LDAP://" + ldapDomain;
            DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            // all that have employeenumber set
            mySearcher.Filter = "(&(objectCategory=Person)(objectClass=User)(employeeNumber=*))";

            // all WITHOUT employeenumber set
            // mySearcher.Filter = (&(objectCategory=Person)(objectClass=User)(!(employeeNumber=*)))";
            mySearcher.PageSize = 10;

            var results = SafeFindAll(mySearcher);

            mySearcher.Dispose();
            return results;
        }

        public static string FriendlyDomainToLdapDomain(string friendlyDomainName)
        {
            string ldapPath = null;
            try
            {
                DirectoryContext objContext = new DirectoryContext(
                    DirectoryContextType.Domain, friendlyDomainName);
                Domain objDomain = Domain.GetDomain(objContext);
                ldapPath = objDomain.Name;
            }
            catch (DirectoryServicesCOMException e)
            {
                ldapPath = e.Message.ToString();
            }
            return ldapPath;
        }

        private static IEnumerable<SearchResult> SafeFindAll(DirectorySearcher searcher)
        {
            using (var results = searcher.FindAll())
            {
                foreach (var result in results)
                {
                    yield return (SearchResult)result;
                }
            } // SearchResultCollection will be disposed here
        }
    }
}

答案 2 :(得分:-1)

找到用户的两种方法

var userName = Request.ServerVariables["LOGON_USER"];
var pc = new PrincipalContext(ContextType.Domain);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);

string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"someUserName")) 
    {
        if (user != null)
        {
            fullName = user.DisplayName;
        }
    }
}