Query Details

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:

  1. Define a Regex Pattern:

    • The query starts by defining a regular expression pattern (OUPattern) to identify and capture the organizational unit part of the OnPremisesDistinguishedName. The pattern is designed to skip over the initial "CN=" part if it exists and capture the rest.
  2. Filter and Process Data:

    • It looks at the IdentityInfo table, 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).
  3. Filter by Group Membership:

    • The query further filters the accounts to include only those that are members of specific AD groups (LAPS_Global_Workplace_Reset and LAPS_Servers_Reset).
  4. Extract the OU:

    • It uses the previously defined regex pattern to extract the organizational unit from the OnPremisesDistinguishedName field.
  5. Select Relevant Information:

    • Finally, it projects (selects) specific fields to display: AccountUPN, AccountName, OnPremisesDistinguishedName, the extracted OU, and GroupMembership.

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 profile picture

Alex Verboon

Released: April 16, 2026

Tables

IdentityInfo

Keywords

ActiveDirectoryIdentityInformationAccountOrganizationalUnitGroupMembership

Operators

letdynamicwhereagosummarizearg_maxbyhas_anyextendextractproject

Actions

GitHub