How to filter users in Active Directory for InActive Users in .Net?
I want to create a filter to fetch all the Active users in Active directory, I used this filter but it didn开发者_如何学Python't worked
searcher.Filter = string.Format(
System.Threading.Thread.CurrentThread.CurrentCulture,
"(&(|(samaccountname={0})(mailnickname={0}))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
alias);
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace.
You can use a PrincipalSearcher
and a "query-by-example" principal to do your searching:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a UserPrincipal
// which is not enabled (not active)
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Enabled = false;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement
Grab adfind from www.joeware.net and you can use it to test filters - adfind -f "<your filter here>"
-default will do the trick.
What you pasted looks accurate although I would further scope it to users only like this:
(&(objectClass=user)(objectCategory=person)(|(samaccountname={0})(mailnickname={0}))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
精彩评论