On this page

Querying Active Directory (AD) Objects with PowerShell

Updated on June 22, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Active Directory (AD) is the central identity store for most Windows enterprise environments, containing user accounts, groups, computers, organizational units, and many other object types. PowerShell provides a dedicated module—installed through RSAT—that exposes a rich set of cmdlets for querying these objects in a structured, predictable way. The ActiveDirectory module includes cmdlets such as Get-ADUser, Get-ADGroup, Get-ADComputer, Get-ADOrganizationalUnit, and Get-ADObject, each supporting server-side filtering, property selection, and search scoping. By understanding the hierarchical structure of AD and mastering these cmdlets, administrators can build efficient, scalable automation for identity management, auditing, compliance reporting, and directory analysis.


Understanding AD Objects and the Directory Structure​

Active Directory organizes information into a hierarchical structure. At the highest level, the directory contains:

Each object has:

PowerShell interacts with these objects through cmdlets that map directly to AD classes. The distinguished name follows a hierarchical format: CN=Username,OU=Users,DC=contoso,DC=com.


The Active Directory PowerShell Module​

Once RSAT is installed, the ActiveDirectory module becomes available. It provides cmdlets such as:

Each cmdlet retrieves a specific type of object, and each supports filtering, property selection, and scoping.

Before querying AD, import the module:


Import-Module ActiveDirectory

Code explanation: The Import-Module cmdlet loads the ActiveDirectory module into the current PowerShell session. This makes all AD-specific cmdlets available for use. If the module loads successfully, no output is displayed. If it fails, PowerShell returns an error indicating that the module could not be found, which typically means RSAT is not installed.

To verify that the module is available:


Get-Module -Name ActiveDirectory -ListAvailable

Code explanation: This command checks whether the ActiveDirectory module is installed and available for import. If the module exists, it returns the module's name, version, and path.


Querying Users​

Users are one of the most common AD objects to query. PowerShell provides a dedicated cmdlet for this purpose.

Retrieving a Single User​


Get-ADUser -Identity "enrico"

Code explanation: The -Identity parameter accepts a username, distinguished name, GUID, or SID. The cmdlet returns a user object with a default set of properties, including DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, and UserPrincipalName.

Retrieving Additional Properties​

By default, AD cmdlets return only a subset of attributes. To retrieve more:


Get-ADUser -Identity "enrico" -Properties mail, lastLogonDate, department

Code explanation: The -Properties parameter specifies which additional attributes to include in the returned object. This is more efficient than retrieving all properties, as it reduces network traffic and processing time. Commonly requested properties include mail, lastLogonDate, department, title, manager, memberOf, and office.

To retrieve all properties for a user:


Get-ADUser -Identity "enrico" -Properties *

Code explanation: The wildcard (*) retrieves all attributes for the user object. This is useful for discovery but should be used sparingly in production scripts due to performance overhead.

Filtering Users​

The -Filter parameter uses a PowerShell-like syntax that is evaluated by the domain controller, making it efficient:


Get-ADUser -Filter "Enabled -eq 'True'"

Code explanation: This retrieves all enabled user accounts. The filter string uses PowerShell syntax with attribute names and comparison operators. The filter is processed on the domain controller, so only matching objects are returned over the network.

More complex filters can combine conditions:


Get-ADUser -Filter "Enabled -eq 'True' -and Department -eq 'Sales'"

Code explanation: This retrieves all enabled users in the Sales department using the -and logical operator. The filter syntax supports -and, -or, and -not operators.

Filtering by OU​


Get-ADUser -Filter * -SearchBase "OU=Sales,DC=contoso,DC=com"

Code explanation: The -SearchBase parameter restricts the search to a specific organizational unit. The -Filter * retrieves all objects within that OU. This parameter is essential for scoping queries to specific parts of the directory.

Using LDAPFilter​

For complex queries, you can use LDAP syntax with -LDAPFilter:


Get-ADUser -LDAPFilter "(mail=*@contoso.com)"

Code explanation: LDAP filters use standard LDAP syntax with parentheses and attribute names. This example retrieves all users with email addresses in the contoso.com domain. LDAP filters are powerful but require precise syntax.


Querying Groups​

Groups are essential for managing permissions and access control.

Retrieving a Group​


Get-ADGroup -Identity "Domain Admins"

Code explanation: This retrieves the Domain Admins group object. The -Identity parameter accepts the group name, distinguished name, or SID. By default, only the group's core properties are returned.

Retrieving Group Members​


Get-ADGroupMember -Identity "Domain Admins"

Code explanation: This cmdlet returns users, groups, and service accounts that belong to the specified group. Each member is returned as an object with properties including DistinguishedName, Name, ObjectClass, and ObjectGUID.

Retrieving Group Members Recursively​

For nested groups, use the -Recursive parameter:


Get-ADGroupMember -Identity "Domain Admins" -Recursive

Code explanation: The -Recursive parameter traverses nested group memberships, returning all members at any depth of nesting. This is essential for determining effective membership.

Filtering Groups​


Get-ADGroup -Filter "GroupCategory -eq 'Security'"

Code explanation: This retrieves all security groups in the domain. The GroupCategory attribute distinguishes security groups (Security) from distribution groups (Distribution).

To retrieve groups with a specific name pattern:


Get-ADGroup -Filter "Name -like '*-Admin'"

Code explanation: This retrieves all groups whose names end with -Admin. The -like operator supports wildcard matching.


Querying Computers​

Computer objects represent domain-joined machines.

Retrieving a Computer​


Get-ADComputer -Identity "PC-01"

Code explanation: This retrieves the computer object with the name PC-01. The returned object includes properties such as Name, Enabled, OperatingSystem, and DistinguishedName.

Retrieving Additional Properties​


Get-ADComputer -Identity "PC-01" -Properties OperatingSystem, LastLogonDate

Code explanation: This retrieves the computer object with the operating system name and last logon date included. These properties are useful for inventory and compliance tasks.

Filtering Computers​


Get-ADComputer -Filter "OperatingSystem -like '*Windows 11*'"

Code explanation: This retrieves all computers running Windows 11. The -like operator with wildcards matches partial operating system names.

To find computers that are enabled:


Get-ADComputer -Filter "Enabled -eq 'True'"

Code explanation: This retrieves all enabled computer accounts. Disabled computer accounts are often stale and can be candidates for cleanup.


Querying Organizational Units (OUs)​

OUs are containers used to organize objects and apply Group Policy.

Retrieving All OUs​


Get-ADOrganizationalUnit -Filter *

Code explanation: This retrieves all organizational units in the domain. Each OU object includes properties such as Name, DistinguishedName, Description, City, Country, and PostalCode.

Filtering OUs by Name​


Get-ADOrganizationalUnit -Filter "Name -like '*Servers*'"

Code explanation: This retrieves OUs whose names contain "Servers". This is useful for locating OUs related to server infrastructure.

Filtering OUs with Protected Deletion​


Get-ADOrganizationalUnit -Filter "ProtectedFromAccidentalDeletion -eq 'True'"

Code explanation: This retrieves OUs that have accidental deletion protection enabled. This is important for identifying OUs that contain critical objects.


Querying Generic AD Objects with Get-ADObject​

Some objects do not fit neatly into the user/group/computer categories. Get-ADObject provides a more general interface.

Retrieving All Service Connection Points​


Get-ADObject -Filter "ObjectClass -eq 'serviceConnectionPoint'"

Code explanation: This retrieves all service connection point objects in the directory. Service connection points are used by applications to publish connection information.

Retrieving Deleted Objects​

If the Active Directory Recycle Bin is enabled:


Get-ADObject -Filter * -IncludeDeletedObjects

Code explanation: The -IncludeDeletedObjects parameter includes deleted objects in the query results. This is useful for recovery and auditing scenarios. Deleted objects have a distinguishedName that includes the CN=Deleted Objects container.

Retrieving Objects by ObjectClass​


Get-ADObject -Filter "ObjectClass -eq 'container'"

Code explanation: This retrieves all container objects, which include OUs and other container types.


Working with Filters and Search Bases​

Filtering is one of the most important aspects of querying AD.

Using Filter Syntax​

The filter is evaluated by the domain controller, making it efficient. The syntax uses attribute names and comparison operators:

OperatorDescription-eqEquals-neNot equals-likeWildcard match-notlikeWildcard not match-gtGreater than-ltLess than-andLogical AND-orLogical OR-notLogical NOT

Example with date comparison:


Get-ADUser -Filter "lastLogonDate -lt '2024-01-01'"

Code explanation: This retrieves users whose last logon date is before January 1, 2024. Date values in filters should be in a format that the domain controller can parse.

Using SearchBase with Different Scopes​

The -SearchBase parameter accepts a distinguished name. The -SearchScope parameter controls how deep the search goes:

ScopeDescriptionBaseOnly the base objectOneLevelImmediate children onlySubtreeEntire subtree (default)

Example with OneLevel scope:


Get-ADUser -Filter * -SearchBase "OU=Sales,DC=contoso,DC=com" -SearchScope OneLevel

Code explanation: This retrieves only users directly in the Sales OU, excluding users in any sub-OUs. This is useful for scoping queries to specific groups of objects.

Using Server Parameter​

By default, AD cmdlets target the closest domain controller. To specify a specific domain controller:


Get-ADUser -Filter * -Server "DC01.contoso.com"

Code explanation: The -Server parameter specifies which domain controller to query. This is useful for load balancing, testing, or when a specific DC is known to have the most up-to-date data.


Practical Administrative Scenarios​

Finding Inactive User Accounts​

To identify user accounts that have been inactive for a specified period:


$inactiveDate = (Get-Date).AddDays(-90)

Get-ADUser -Filter * -Properties lastLogonDate |

    Where-Object { $_.lastLogonDate -lt $inactiveDate }

Code explanation: The script first calculates the cutoff date (90 days ago). It then retrieves all user accounts with the lastLogonDate property. The Where-Object filter selects only users whose last logon date is earlier than the cutoff date. This is useful for identifying accounts that can be disabled or removed.

Listing All Domain Controllers​


Get-ADDomainController -Filter *

Code explanation: This cmdlet retrieves all domain controllers in the current domain. Each returned object includes the computer name, site, and IP address.

Retrieving All Members of a Nested Group​


Get-ADGroupMember -Identity "Helpdesk" -Recursive |

    Where-Object { $_.objectClass -eq 'user' }

Code explanation: This retrieves all members of the Helpdesk group, recursively traversing nested groups, and filters to only user objects. This provides a complete list of users who have access through the group.

Finding Computers That Have Not Logged In Recently​


$cutoff = (Get-Date).AddDays(-60)

Get-ADComputer -Filter * -Properties lastLogonDate |

    Where-Object { $_.lastLogonDate -lt $cutoff }

Code explanation: This retrieves all computer accounts with the lastLogonDate property and filters to those whose last logon date is earlier than 60 days ago. Such computers are often candidates for cleanup.

Exporting User Information to CSV​


Get-ADUser -Filter * -Properties mail, department, title, manager |

    Select-Object SamAccountName, Name, mail, department, title,

        @{N='Manager';E={$_.manager -replace '^CN=([^,]+).*$','$1'}} |

    Export-Csv -Path "C:\reports\users.csv" -NoTypeInformation

Code explanation: This script retrieves all users with several additional properties. The Select-Object cmdlet selects specific properties and includes a calculated property for Manager that extracts only the manager's name from the distinguished name. The results are exported to a CSV file for reporting or analysis.

Finding Groups with No Members​


Get-ADGroup -Filter * |

    ForEach-Object {

        $members = Get-ADGroupMember -Identity $_.Name -ErrorAction SilentlyContinue

        if ($members -eq $null) {

            $_

        }

    }

Code explanation: This retrieves all groups, checks each group's members, and returns only groups that have no members. Empty groups are candidates for removal or review.


Summary​

Querying Active Directory objects is one of the most important skills for Windows administrators. PowerShell provides a dedicated module that allows you to:

By mastering these techniques, you gain the ability to explore and analyze your directory environment with precision, enabling automation and insight at scale.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Installing RSAT

Next

Creating and Modifying Users, Groups and Computers