Here’s a one-liner you can use to quickly find empty organizational units in your Active Directory:
Get-QADObject -Type organizationalUnit -DontUseDefaultIncludedProperties | where { -not ( Get-QADObject -SearchRoot $_.DN -DontUseDefaultIncludedProperties ` -SearchScope OneLevel -SizeLimit 1 -WarningAction SilentlyContinue ) }
A quick explanation of what I am doing here:
- I am retrieving all
organizationalUnitobjects from my domain (and use the-DontUseDefaultIncludedPropertiesswitch to save a few milliseconds
) - Then for each of the OUs I am retrieving all AD objects that are in that OU by doing a
Get-QADObjectand limiting the search scope to the DN of the current OU. - Note that (like we did when looking for large groups) I am using the
-SizeLimitparameter to see if I can get 1 item in the call (all I need is to learn whether there is anything in the OU – I don’t need the whole list) – which obviously makes the whole script magnitudes of time faster. I use -SearchScope - Based on Kirk’s recommendation I am using
-SearchScope OneLevelto exclude the OU itself. - I am using -not operator so I get only the OUs for which this Get-QADObject evaluates to
$null(nothing found) and thus-not $nullevaluates to$true.
P.S. This is the code I was using initially, which I then corrected based on Kirk’s comments below:
$emptyOUs = Get-QADObject -Type organizationalUnit -DontUseDefaultIncludedProperties | where {(Get-QADObject -SearchRoot $_.DN -SizeLimit 2 -DontUseDefaultIncludedProperties).Count -lt 2}
Tags: AD, AD cmdlets, Active Directory, Examples, PowerShell, cmdlets, one-liner
Subscribe by email




I think it’s cleaner if you set SizeLimit to 1 and set the -SearchScope parameter to OneLevel. That makes Get-QADObject return only children, not the object itself. Searching for 2 objects in the Where-Object clause seems just odd to me for some reason.
Plus, if you take that approach, you can dump your -gt 2 and have Where-Object simply test for the presence of children.
Awesome! Thanks Kirk. I’ll update the post right away!