List user objects and count them
List user objects and count them

There are several ways to list specific Active Directory objects. I will show you two ways : using the instance of the System.DirectoryServices.DirectoryEntry class or using the powershell cmdlet Get-ADObject

$ldapQuery = "(&(objectCategory=user)(objectClass=user))"
$de = new-object system.directoryservices.directoryentry
$ads = new-object system.directoryservices.directorysearcher -argumentlist $de,$ldapQuery
$ads.Pagesize = 100000
$complist = $ads.findall()
# count user object
$complist.Count
# list user objects
$complist
$list = get-adobject -ldapfilter "(&(objectCategory=user)(objectClass=user))"
# count user object
$list.Count
# list user objects
$list

The interesting point is the performance between these methods. To check that we can use the powershell cmdlet Measure-Command . The result is :

PS > Measure-Command {
    $ldapQuery = "(&(objectCategory=user)(objectClass=user))"
    $de = new-object system.directoryservices.directoryentry
    $ads = new-object system.directoryservices.directorysearcher -argumentlist $de,$ldapQuery
    $ads.Pagesize = 100000
    $complist = $ads.findall()
    $complist.Count
}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 23
Milliseconds      : 418
Ticks             : 234188882
TotalDays         : 0.000271051946759259
TotalHours        : 0.00650524672222222
TotalMinutes      : 0.390314803333333
TotalSeconds      : 23.4188882
TotalMilliseconds : 23418.8882
PS > Measure-Command {
    $list = get-adobject -ldapfilter "(&(objectCategory=user)(objectClass=user))"
    $list.Count
}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 3
Milliseconds      : 513
Ticks             : 35130302
TotalDays         : 4.06600717592593E-05
TotalHours        : 0.000975841722222222
TotalMinutes      : 0.0585505033333333
TotalSeconds      : 3.5130302
TotalMilliseconds : 3513.0302

You will find more information on the powershell cmdlet Measure-Command here:

Measures the time it takes to run script blocks and cmdlets.
Syntax
PowerShell

Measure-Command
[-Expression]
[-InputObject ]
[]

Description

The Measure-Command cmdlet runs a script block or cmdlet internally, times the execution of the operation, and returns the execution time.

<>

My Powershell script categories

List user objects and count them

Leave a Reply

Your email address will not be published. Required fields are marked *