Mich
Mich

Reputation: 322

Fastest way to count ad users in PowerShell?

I've been looking for the fastest way to count the number of ad users in powershell, aswell as the number of enabled and disabled users, but the queries are very long (~100k users, 1-2 min per query) and my powershell ISE usually crashes after one or two requests (it's for a reporting job)

So my question is how can I optimize these queries :

$CountADUsers = (get-aduser –filter * -server $myserver).count.Count
$CountADUsersEnabled = (get-aduser -filter * -server $myserver | where {$_.enabled -eq "True"}).count
$CountADUsersNotEnabled = $CountADUsers - $CountADUsersEnabled

Thanks in advance guys

Upvotes: 2

Views: 8275

Answers (1)

Robert Dyjas
Robert Dyjas

Reputation: 5227

You don't need to run Get-AdUser twice. You can save it to variable and just filter it:

$allUsers = get-aduser –filter * -server $myserver
$CountADUsers = $allUsers.count
$CountADUsersEnabled = ($allUsers | where {$_.enabled -eq "True"}).count

Also, it won't be helpful in that case, but please remember that using -Filter * and then Where-Object is not very effective as you can just use:

Get-ADUser -Filter {enabled -eq "True"}

Another hint: ISE shouldn't be used for running scripts as it sometimes behave in strange ways (especially when you run out of memory on your machine). You should use powershell.exe instead.

Edit: to improve even more you could try to choose only the attributes you need using

$t = $allusers |select userprincipalname,enabled

And then use Where-Object to filter. For comparison:

Measure-command {($allusers | where {$_.enabled -eq "True"}).count}

took two minutes when

Measure-command {($t | where {$_.enabled -eq "True"}).count}

took two seconds (but selecting takes about 2 mins so the overall time is more or less the same). However, this strongly depends on the scenario. I'll leave it to you so you can find the best solution for your case. Remember, Measure-Command is your very good friend for this!

Upvotes: 4

Related Questions