Find accounts in an unexpected OU
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
Script reader
Inspect before you run
Inspect the script below. It does not run in this browser.
Inspection only — no command has run.
Show reference output
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- Stage 1Get-ADUser
-Filter - Stage 2Where-Object
-notmatch - Stage 3Select-Object
Positional 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.
- 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.