none
Get the object count details for OU's in Active Directory RRS feed

  • Question

  • Hi Guys,

    I'm looking for the powershell commands/script to get the number of objects in the OU's. I have OU's canonical name and is there any way to get the object counts.

    Thanks in advance.

    • Moved by Bill_Stewart Friday, March 15, 2019 6:19 PM This is not "scripts on demand"
    Tuesday, January 22, 2019 4:04 PM

All replies

  • You cannot filter on canonicalName because it is operational (also called constructed). And you cannot bind to the object with canonicalName. You need the distinguished name of the OU.

    One solution would be similar to:

    $OU = "ou=Sales,ou=West,dc=Domain,dc=com"
    
    $D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Domain = [ADSI]"LDAP://$D"
    
    $Searcher1 = New-Object System.DirectoryServices.DirectorySearcher
    $Searcher1.PageSize = 200
    $Searcher1.SearchScope = "OneLevel"
    $Searcher1.Filter = "(objectCategory=*)"
    $Searcher1.PropertiesToLoad.Add("distinguishedName") > $Null
    $Searcher1.SearchRoot = "LDAP://" + $OU
    
    $DNs = $Searcher1.FindAll()
    $Count = $DNs.Count
    "Objects in $OU : $Count"


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)


    Tuesday, January 22, 2019 4:41 PM
  • Tuesday, January 22, 2019 6:11 PM
  • Once you have converted the canonicalName to distinguishedName, another solution is to use Get-ADObject. But you still cannot filter on canonicalName. And objects are not members of their parent OU. The only attribute indicating parent OU/Container is distinguishedName. But you can use the -SearchBase parameter to retrieve all objects in a specified OU.

    $OU = "ou=Sales,ou=West,dc=Domain,dc=com"
    $Count = (Get-ADObject -SearchBase $OU -SearchScope OneLevel -Filter *).Count
    "Objects in $OU : $Count"

    Note that this count includes users, contacts, computers, groups, and child OUs. This also applies to the first script example I posted above.


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)



    Tuesday, January 22, 2019 6:34 PM
  • To avoid recursion add "-SearchScope OneLevel"

    \_(ツ)_/

    Tuesday, January 22, 2019 6:40 PM
  • Good point about -SearchScope. I updated the code in my reply.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Tuesday, January 22, 2019 6:45 PM
  • Good point about -SearchScope. I updated the code in my reply.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    I knew you forgot. 


    \_(ツ)_/

    Tuesday, January 22, 2019 6:52 PM