PowerShell Problem Solver: Finding Empty Organizational Units in Active Directory
Posted on April 13, 2016 by Jeff Hicks in PowerShell
https://www.petri.com/powershell-problem-solver-finding-empty-organizational-units-active-directory
I was working with another "this will be easy" task today. Search for ALL of the OUs that do not have any user or computer objects in them, basically Empty OUs.
Jeff's example was spot on and I didn't even have to do anything to them once found just dump them to a file to be worked later.
Code:
Get-ADOrganizationalUnit -filter * -Properties Description -PipelineVariable pv | Select DistinguishedName,Name,Description,
@{Name="Children"; Expression = {Get-ADObject -filter * -SearchBase $pv.distinguishedname |
Where { $_.objectclass -ne "organizationalunit"} |
Measure-Object | Select -ExpandProperty Count }} | Where {$_.children -eq 0}
Get-ADOrganizationalUnit : The server has returned the following error: invalid enumeration context.
At line:1 char:14
+ ... Testing02 = Get-ADOrganizationalUnit -filter * -Properties Descriptio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : The server has returned the following error: invalid enumeration context.,Microsoft.ActiveDirectory.Management.Commands.GetADOrganizationalUnit
Huh..?
After some digging I realized there may be a limitation on what can be returned similar to what I had ran into while working with results from Exchange & Lync.
The answer for me - due to our size - was to include the -ResultPageSize switch which I set to 0.
Code:
Get-ADOrganizationalUnit -filter * -ResultPageSize 0 -Properties Description -PipelineVariable pv | Select DistinguishedName,Name,Description,
@{Name="Children"; Expression = {Get-ADObject -filter * -SearchBase $pv.distinguishedname |
Where { $_.objectclass -ne "organizationalunit"} |
Measure-Object | Select -ExpandProperty Count }} | Where {$_.children -eq 0}
BINGO!
Now I checked a couple to see if I had what I wanted then I dumped it to a file for the requester.
Thanks Jeff!!