AD PowerShell Tip: How to Find Unused Organizational Units in Active Directory

 

This is a quick tip I recently discovered and wanted to share.  The Active Directory PowerShell Module also displays constructed attributes in results.  One useful attribute I use for Organizational Units (OU) is msDS-Approx-Immed-Subordinates, this attribute returns the number of direct descendants under any OU or container in Active Directory. Its doesn’t seem to be something that you can use in a filter but you can use it in your where-object clause.

 #get all ou's and the number of direct descendants 
 get-adorganizationalunit -filter * -properties "msDS-Approx-Immed-Subordinates" | select `
     name, "msDS-Approx-Immed-Subordinates", distinguishedname
 #get ou's with no direct descendant
 get-adorganizationalunit -filter * -properties "msDS-Approx-Immed-Subordinates" | select `
     name, "msDS-Approx-Immed-Subordinates", distinguishedname | `
         where {$_."msDS-Approx-Immed-Subordinates" -eq 0}
 #get ou's with direct descendants
 get-adorganizationalunit -filter * -properties "msDS-Approx-Immed-Subordinates" | select `
     name, "msDS-Approx-Immed-Subordinates", distinguishedname | `
         where {$_."msDS-Approx-Immed-Subordinates" -ne 0}

image

image

I put together a sample script to find and delete unused Organizational Units.

GitHub: FindandDeleteUnusedOUs.ps1

Hope you find this useful.

-Chad