Answered fine empty's OU in AD DS

  • Tuesday, February 19, 2013 7:41 AM
     
     

    how can I find just all Empty OU in AD DS without use ?

    Parent OU and child OU

All Replies

  • Tuesday, February 19, 2013 12:14 PM
     
     Answered Has Code

    This is very inefficient way but may work for You:

    Get-ADOrganizationalUnit -Filter * | Where-Object {
        @(Get-ADObject -Filter * -SearchBase $_).Count -eq 1
    }

  • Tuesday, February 19, 2013 7:49 PM
    Moderator
     
     

    There is no way too query for empty OU's, except to count (retrieve all children), as suggested.


    Richard Mueller - MVP Directory Services

  • Wednesday, February 20, 2013 6:23 AM
     
     Answered Has Code

    Like the others have said, there is no direct way of doing this.  But if you give it some thought you may come up with something like this which I think is more efficient:

    
    
    (New-Object System.DirectoryServices.DirectorySearcher ("(objectclass=organizationunit)",@(1.1))).FindAll() | ? {
    	-not (New-Object System.DirectoryServices.DirectorySearcher ($_.GetDirectoryEntry(), "(objectclass=*)", @(1.1), [System.DirectoryServices.SearchScope]::OneLevel)).FindOne()
    } | Select Path


    The above will give you the ADsPath of all empty OUs (no children) in your domain.  However if you consider OUs that include empty OUs empty, just change the second filter from (objectclass=*) to (&(!objectclass=organizationunit)(!objectclass=container)), and change the scope from OneLevel to Subtree.


    It's not considered memory efficient since it doesn't release the memory of the objects but I bet you don't have thousands of OUs so it's fine I think.