My specific Question: How to I narrow down my search for active directory accounts that DO NOT have employeeNumber attribute set (is not null or empty)?
My work around is to go over the results and check the employeeNumber and removing those accounts. However, I would like my query to narrow down the results before I have to filter then manually.
The line that I think is not even firing a filter : ((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
}