Friday, 10 April 2015

AD Powershell: Count AD Users with OU structure


In order to count users in specified OU's it is needed to create an empty matrix and add value any time that user account appears in the search loop.
I must admit that part of this script is borrowed from some other admin, but don't remember the link now.

In $filepath choose output file path, in Line 4 ($ou=) change searchbase filter to your root OU.
THANKS to David (see comments below-changes bold in the text), the script is little modified, to work better.

Import-Module ActiveDirectory
$outmatrix = @()
$ou=Get-ADOrganizationalUnit -searchbase "OU=RootOU, DC=Domain, DC=Com" -filter * -searchscope 1
foreach ($o in $ou)
{$count=@(Get-ADUser -searchbase $o -filter * |Where-Object {$_.enabled -eq "true"}).count

#Construct an object
        $matrix = "" | Select "ou", "count"
        $matrix.ou = $o
        $matrix.count = $count
        $outmatrix += $matrix
$matrix = $null
$outmatrix |export-csv $filepath -notypeinformation