LDAP queries can be used to search for different objects according to certain criteria (computers, users, groups) in the Active Directory LDAP database. To perform an LDAP query against the AD LDAP catalog, you can use various utilities (for example, ldapsearch in Windows), PowerShell or VBS scripts, Saved Queries feature in the Active Directory Users and Computers MMC snap-in, etc.
In this article, we’ll take a look at some useful examples of LDAP queries to AD and how to execute them.
How to Execute the LDAP Query?
First, let’s look at some examples of executing LDAP (Lightweight Directory Access Protocol) queries. For example, you want to perform a simple LDAP query to search for Active Directory users which have the “User must change password at next logon” option enabled. LDAP filter code must be surrounded by parentheses(). The code for this LDAP query is as follows:
(objectCategory=person)(objectClass=user)(pwdLastSet=0)(!useraccountcontrol:1.2.840.113556.1.4.803:=2)
Let’s try to execute this LDAP query using the AD snap-in.
- Open the ADUC console and go to the Saved Queries section;
- Create a new query: New > Query;
- Specify a name for the new saved query. Click the Define Query button;
- Select the Custom Search type. Go to the Advanced tab, and copy your LDAP query code into the Enter LDAP query field;
- Click OK twice. Select your new query in the ADUC Saved Queries tree. Then press F5;
- A list of AD users that match this LDAP query should display on the right pane.
You can also use LDAP filters when searching for objects in the ADSI Edit console.
- To add an LDAP filter, click on the selected naming context (NC). Then select New > Query from the menu;
- Set the query name;
- Select the search area (Root of Search). In the Query String field specify the code of your LDAP filter. Additionally, here you can select the depth of the search Subtree or One level.
You can also use the LDAP query filter in the following PowerShell cmdlets: Get-ADUser, Get-ADComputer, Get-ADGroup, and Get-ADObject (these cmdlets are part of the PowerShell Active Directory module). Each of these cmdlets has a LdapFilter parameter, which was specifically designed to use LDAP filters when searching for objects in Active Directory.
For example, we will execute the above LDAP search query using Get-ADUser. Open the powershell.exe console, and run the command:
Get-ADUser -LDAPFilter '(objectCategory=person)(objectClass=user)(pwdLastSet=0)(!useraccountcontrol:1.2.840.113556.1.4.803:=2)'
To search for computers, use the Get-ADComputer cmdlet:
Get-ADComputer –LDAPFilter ‘your ldap query’
For example, you want to search for all desktop computers in Active Directory with certain versions of Windows that do not contain the keywords WKS and TEST in their names. First, let’s create a complex LDAP filter with several OR conditions:
$compLDAPFilter= "(&(|(operatingSystem=*Windows 7*)" $compLDAPFilter+= "(operatingSystem=*Windows 8*)" $compLDAPFilter += "(operatingSystem=*Windows 8.1*)" $compLDAPFilter += "(operatingSystem=*Windows 10*))" $compLDAPFilter += "(!name=*WKS*)(!name=*TEST*))"
After you have created an LDAP filter, it can be executed via Get-ADComputer:
Get-ADComputer -LDAPFilter $compLDAPFilter -Property * | Select-Object Name, OperatingSystem, LastLogonDate
To search for Active Directory group in AD, use the Get-ADGroup cmdlet:
Get-ADGroup –LDAPFilter {LDAP_query}
If you don’t know the type of Active Directory object you are looking for, you can use the generic Get-ADObject cmdlet:
Get-ADObject -LdapFilter "(cn=*Brion*)"
In this example, we found that the given LDAP filter matches the user Jon Brion and the BrionTeam group.
If you need to find objects of a specific type, you can specify the object type using the objectClass parameter. For example:
Get-ADObject -LdapFilter "(&(objectClass=user)(cn=*Brion*))"
Let’s look at another example that allows you to display a list of users with membership in a specific group in Active Directory. In this example, we get a list in the Domain Admins group, but you can replace the group name with the Group CN you want:
(Get-ADObject -LdapFilter “(&(objectclass=group)(CN=Domain Admins))”) | ForEach-Object {$a=$_.Name; Get-ADObject -LdapFilter “(&(objectclass=user)(MemberOf=$($_.DistinguishedName)))” | Select-Object DistinguishedName, Name, @{l=’GroupName’;e={$a}}}
Here is another example that allows you to get a list of computers in a group. If user accounts are added to the group, such an LDAP query will not include them in the search results:
(Get-ADObject -LdapFilter “(&(objectclass=group)(CN=caManagerComputers))”) | ForEach-Object {$a=$_.Name; Get-ADObject -LdapFilter “(&(objectclass=computer)(MemberOf=$($_.DistinguishedName)))” | Select-Object DistinguishedName, Name, @{l=’GroupName’;e={$a}}}
Windows has several built-in tools such as dsget and dsquery. These tools allow you to run LDAP queries against Active Directory,
The dsquery utility returns the Distinguished Name of an object that matches the specified parameters (for LDAP filters it has a filter parameter). For example, to find all users with job titles starting with Manager, run the command:
dsquery * OU=Employees,DC=theitbros,DC=com -filter "(&(objectCategory=person)(objectClass=user)(Title=Manager*))"
You can use ANR (Ambiguous Name Resolution) to search for objects in Active Directory. This AD feature allows you to use complex filters that include several attributes associated with names:
- displayName
- givenName (First Name)
- sn (Last Name)
- sAMAccountName
- legacyExchangeDN
- Relative Distinguished Name (RDN)
- proxyAddresses
- mailNickname
- msExchResourceSearchProperties
- msDS-AdditionalSamAccountName
- msDS-PhoneticCompanyName
- msDS-PhoneticDepartment
- msDS-PhoneticDisplayName
- msDS-PhoneticFirstName
- msDS-PhoneticLastName
For example, to find users that contain the keyword test in one of these attributes, it’s enough to run this simple LDAP query:
(anr=test)
LDAP Filter Syntax
The text form of LDAP search filters is defined in RFC 4515. The syntax for an LDAP filter is:
<Filter>=(<Attribute><comparison operator><value>)
The following comparison operators can be used in a filter:
Operator | |
= | Equal |
>= | More or equal |
<= | Less or equal |
~= | Approximately equal |
For example, the following filter returns all objects with cn (common name) attribute value Jon:
(cn=Jon)
Filters can be combined using boolean operators when there are multiple search conditions:
Operator | |
& | AND — all conditions must be met |
| | OR — any number of conditions can be met |
! | NOT — the condition must not be met |
For example, let’s select AD objects with cn equal to Jon and sn (surname) equal to Brion:
(&(cn=Jon)(sn=Brion))
You can use several logical operators in one filter at once, the main thing is not to get confused in parentheses. Let’s compose a filter that will return objects with cn equal to Jon or sn equal to Brion, for which cn is not equal to Alex:
(&(|(cn=Jon)(sn=Brion)(!(cn=Alex)))
You can refine search objects using the objectCategory and objectClass attributes.
Valid parameters: person, user, contact, computer, groups, organizationalPerson.
Using the following filter, select all users named Jon:
(&(objectClass=user)(objectCategory=person)(cn=Jon))
If you don’t know the exact name of the object, you can use the * wildcard character in the LDAP filter. For example, the previous query to find users whose name starts with Jo would need to be changed to:
(&(objectClass=user)(objectCategory=person)(cn=Jo*)) Get-ADObject -LdapFilter "(&(objectClass=user)(objectCategory=person)(cn=Jo*))" -properties givenName|select givenName
LDAP Query Examples for Active Directory
Let’s consider some useful examples of LDAP queries that are often used by AD admins.
Search for administrators in groups Domain Admins, Enterprise Admins:
(objectClass=user)(objectCategory=Person)(adminCount=1)
List all AD users except blocked ones:
(objectCategory=person)(objectClass=user)(!useraccountcontrol:1.2.840.113556.1.4.803:=2)
Display the list of disabled user accounts:
(objectCategory=person)(objectClass=user)(useraccountcontrol:1.2.840.113556.1.4.803:=16)
Select users with the “Password never expires option” enabled:
(objectcategory=user)(userAccountControl:1.2.840.113556.1.4.803:=65536)
Users with empty email values:
(objectcategory=person)(!mail=*)
List users with the Sales specified in the Department field:
(&(objectCategory=person)(objectClass=user)(department=Sales))
You can check AD group membership with PowerShell command:
(&(objectclass=user)(samacccountname=*)(MemberOf=CN=UKManagers,OU=Groups,OU=UK,DC=theitbros,DC=com))
You can list the groups the user is a member of:
(&(objectCategory=group)(member=CN=Jon Brion,OU=Employees,DC=theitbros,DC=com))
List all disabled computer accounts in AD:
(&(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=2))
Display all Windows 10 computers:
(objectCategory=computer)(operatingSystem=Windows 10*)
You can only select computers with a specific build of Windows 10:
(&(&(objectCategory=computer)(operatingSystem=Windows 10*)(operatingSystemVersion=*19041*)))
Hint. You can map Windows 10 build to the version according the following table:
Windows 10 Version | Build number |
20H2 | 19042 |
2004 | 19041 |
1909 | 18363 |
1903 | 18362 |
1809 | 17763 |
All domain controllers:
(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))
All member domain servers (except DCs):
(&(objectCategory=computer)(operatingSystem=*server*)(!userAccountControl:1.2.840.113556.1.4.803:=8192))
All MS SQL Server instances in AD:
(&(objectCategory=computer)(servicePrincipalName=MSSQLSvc*))
List of groups created for the specified period:
(objectCategory=group)(whenCreated>=20200101000000.0Z&<=20201201000000.0Z&)
List all empty AD groups:
(objectCategory=group)(!member=*)
List all distribution groups:
(&(objectCategory=group)(!groupType:1.2.840.113556.1.4.803:=2147483648))
Print all groups with the *CIO* key in the group name:
(objectCategory=group)(samaccountname=*CIO*)
Find all Exchange Servers in the domain:
(objectCategory=computer)(servicePrincipalName=exchangeMDB*)(operatingSystem=Windows Server*)
All color printers on a specific print server published in the AD:
(uncName=*lon-prnt*)(objectCategory=printQueue)(printColor=TRUE)
5 comments
how to get attributes value in ad through LDAP
I want a list of members in an AD computer group. I’m not having any success in finding the right cmd or script to run an AD query to list members of a computer group. It seems to work only for user accounts. Any advice is greatly appreciated