PowerShell Genie

Find accounts in an unexpected OU

Script 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Every user object is retrieved, then Where-Object keeps the ones whose DistinguishedName fails to match a regular expression describing the approved containers.

The script

1PS> Get-ADUser -Filter * | Where-Object DistinguishedName -notmatch "OU=(Staff|Admins),DC=contoso,DC=com" | Select-Object SamAccountName,DistinguishedName

Script reader

Inspect before you run

Inspection only

Inspect the script below. It does not run in this browser.

Inspection only — no command has run.

    Show reference output
    1 SamAccountName DistinguishedName
    2 -------------- -----------------
    3 sample.user CN=Sample User,OU=Users,DC=example,DC=test
    Inspect this example’s structure

    Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

    Get-ADUser -Filter * | Where-Object DistinguishedName -notmatch "OU=(Staff|Admins),DC=contoso,DC=com" | Select-Object SamAccountName,DistinguishedName
    1. Stage 1Get-ADUser-Filter
    2. Stage 2Where-Object-notmatch
    3. Stage 3Select-ObjectPositional values or no named parameters

      How it works

      Every user object is retrieved, then Where-Object keeps the ones whose DistinguishedName fails to match a regular expression describing the approved containers. The projection pairs the account name with its full DN so the real location is visible rather than inferred from the display name.

      Adapting it

      That regex hardcodes OU=Staff, OU=Admins and a contoso.com domain, so it is the first thing to edit. Reading the approved paths from a text file keeps the check maintainable as the structure changes.

      Requirements

      ActiveDirectory module.

      If the result is unexpected

      The unexpected-OU report flags valid accounts or misses moved users.

      A text comparison against DistinguishedName can confuse similar OU names or ignore nested OU policy.

      1. Inspect the full distinguished name and define whether sub-OUs are allowed.

      Validate the result

      Sample accounts are classified according to the documented OU boundary.

      Keep the check reliable

      Use explicit OU distinguished names and review the rule after directory reorganizations.

      Primary documentation

      PowerShell objects and pipelines documentation

      Continue
      Genie guideFind accounts in an unexpected OU

      Every user object is retrieved, then Where-Object keeps the ones whose DistinguishedName fails to match a regular expression describing the approved containers.