Friday, 10 April 2015

AD Powershell: Count AD Users with OU structure

Hi,

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
$filepath="c:\temp\CompanyUsers.csv"
$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

Regards,
Maciek

6 comments:

  1. Nice work! One thing though: if the OU contains zero or one enabled user, corresponding column returns "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"

    To correct that, you need to add an @ to force Get-ADUser to return an array:
    $count=@(Get-ADUser -searchbase $o -filter * |Where-Object {$_.enabled -eq "true"}).count

    I also added a line with Import-Module activeDirectory at the start, for convenience.

    ReplyDelete
    Replies
    1. Good advice David, it works better now.
      Thanks

      Delete
  2. Hi,

    In the for loop, I added -searchscope 1 since I have nested OU's and each OU contains users, including the parent OU.

    I also changed it to report for ALL OU's in the domain by modifying the first part to exclude "-searchscope 1" and "-searchbase".

    $filepath="c:\temp\CompanyUsers.csv"
    $outmatrix = @()
    $ou=Get-ADOrganizationalUnit -filter * #-searchbase "OU=RootOU, DC=Domain, DC=Com" -filter * -searchscope 1
    foreach ($o in $ou)
    {$count=@(Get-ADUser -searchbase $o -searchscope 1 -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

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Also, in verifying data, the {$_.enabled -eq "true"} should be {$_.enabled -eq $True}.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete