Finding Active Directory User Accounts Fast

by Oct 25, 2013

The more specific your LDAP query is the faster and less resource intense the query is, and the more precise are the results as well.

For example, most people use objectClass to limit search results to a specific object class. To find just user accounts, they often use "objectClass=user". It’s less known that computer accounts are also sharing this object class. Let's check it out:

This example would find all accounts with a SamAccountName that starts with "a" and objectClass="user":

# get all users with a SamAccountName that starts with "a"
$searcher = [ADSISearcher]"(&(objectClass=User)(sAMAccountName=a*))"

# see how long this takes
$result = Measure-Command {
  $all = $searcher.FindAll() 
  $found = $all.Count

$seconds = $result.TotalSeconds

"The search returned $found objects and took $seconds seconds."

Now use this line in the code above instead:

$searcher = [ADSISearcher]"(&(sAMAccountType=$(0x30000000))(sAMAccountName=a*))" 

When you replace this line, the query is significantly faster. And it is more precise, too. That's because the sAMAccountType differentiates between regular user accounts and machine accounts:


  • SAM_MACHINE_ACCOUNT 0x30000001

Both are of objectClass "User".

Twitter This Tip! ReTweet this Tip!