Active Directory - Extract Account OU
AD Extract User OU
Query
let OUPattern = @"^(CN=[^,]+,)?(.+)$";About this query
Active Directory - Extract Account OU
Query Information
Description
Use the below query example to extract the Accounts AD organizational unit from the OnPremisesDistinguishedName
First we define the regex pattern
and then use this regex to extract the OU
| extend OU = extract(OUPattern, 2, OnPremisesDistinguishedName)
References
Microsoft Sentinel / 365 Defender
let ADGroups = dynamic(['LAPS_Global_Workplace_Reset', 'LAPS_Servers_Reset']);
let OUPattern = @"^(CN=[^,]+,)?(.+)$";
IdentityInfo
| where TimeGenerated > ago(90d)
| summarize arg_max(TimeGenerated, *) by AccountName
| where GroupMembership has_any (ADGroups)
| extend OU = extract(OUPattern, 2, OnPremisesDistinguishedName)
| project AccountUPN, AccountName, OnPremisesDistinguishedName, OU, GroupMembership
//| summarize count() by OU
Explanation
This KQL query is designed to extract the organizational unit (OU) from the Active Directory (AD) distinguished name of user accounts. Here's a simple breakdown of what the query does:
-
Define a Regex Pattern:
- The query starts by defining a regular expression pattern (
OUPattern) to identify and capture the organizational unit part of theOnPremisesDistinguishedName. The pattern is designed to skip over the initial "CN=" part if it exists and capture the rest.
- The query starts by defining a regular expression pattern (
-
Filter and Process Data:
- It looks at the
IdentityInfotable, filtering records to only include those generated in the last 90 days. - It summarizes the data to get the most recent entry for each account (
arg_max(TimeGenerated, *) by AccountName).
- It looks at the
-
Filter by Group Membership:
- The query further filters the accounts to include only those that are members of specific AD groups (
LAPS_Global_Workplace_ResetandLAPS_Servers_Reset).
- The query further filters the accounts to include only those that are members of specific AD groups (
-
Extract the OU:
- It uses the previously defined regex pattern to extract the organizational unit from the
OnPremisesDistinguishedNamefield.
- It uses the previously defined regex pattern to extract the organizational unit from the
-
Select Relevant Information:
- Finally, it projects (selects) specific fields to display:
AccountUPN,AccountName,OnPremisesDistinguishedName, the extractedOU, andGroupMembership.
- Finally, it projects (selects) specific fields to display:
This query is useful for administrators who need to analyze and report on the organizational units of user accounts within specific AD groups, particularly in the context of Microsoft Sentinel or 365 Defender environments.
Details

Alex Verboon
Released: April 16, 2026
Tables
Keywords
Operators