For a large customer I had to count the amount of users in different kind of OU’s which were member of different kind of country OU’s. This was needed because the under laying OU’s were used as some sort of Profile Groups. Different people with different roles got added to these groups and we wanted to know how many users would get certain (licensed) applications when we would add an application group to these Profile Groups.

Just change the variables in the script for logfile, country and of course the domain to make this work. You could also extend it by adding more variables or change the current ones. If you need help with this, feel free to contact me.

Note #1: This script makes use of the Active Directory Module for PowerShell.
Note #2: I made some extra variables like $usercount and $groupname for the readability and to make the reporting to a logfile easier. This could be written shortened, but I chose for more readability.

count_ad_users_OU_array.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#######################################################
# AUTHOR  : http://www.hican.net - @hicannet
# DATE    : 21-02-2012
# COMMENT : This script retrieves and counts all users
#           from an array of OU's (countries in this
#           specific case) in Active Directory.
Import-Module ActiveDirectory
# Logfile
$log = "<LOGFILE>"
# OU Array
$country  = "NL","DE","FR","ES","UK"
$country += "AT","RU","PT","SE","US"
# FUNCTIONS
Function getUsers
{
  # Loop through all countries in the $country array
  "-- User Count for sub OU's in each country OU --" | Out-File $log
  Foreach ($cntry In $country)
  {
    "`r`n" + "-- Country - " + $cntry | Out-File $log -append
    $rbacs = Get-ADGroup -Filter * -SearchBase ("OU=Profiles,OU="+$cntry+",OU=Groups,,DC=hican,DC=net")
    Foreach ($rbac In $rbacs)
    {
      If(($rbac | %{$_.Name}) -like "$cntry-Management*" -Or ($rbac | %{$_.Name}) -like "$cntry-Sales*")
      {
        $users   = Get-ADGroupMember $rbac -recursive | Measure-Object
        $usercount = $users | %{$_.Count}
        $groupname = $rbac | %{$_.Name}
        $groupname + " (" + $usercount + ")" | Out-File $log -append
        $usersub   += $usercount
        $usertotal += $usercount
      }
    }
    $cntry + " User Count: " + $usersub | Out-File $log -append
    $usersub = 0
  }
  "`r`n" + "Total User Count: " + $usertotal | Out-File $log -append
  "`r`n" + "--------------------------------------------" + "`r`n" | Out-File $log -append
}
# RUN SCRIPT
getUsers
"SCRIPT FINISHED"