Mar 21 2017

Powershell Count Returns Incorrect Values

Published by at 9:45 pm under Windows

Powershell provides a “count” method that comes first to mind when you have to count lines, files or objects. I was astonished to observe PowerShell would display nothing when it should count 0 or 1.
 
Here’s a screenshot where I retrieve the number of Active Directory accounts and showing count is unreliable.

Powershell incorrect count


Instead use the Measure-Object cmdLet and select the count value that is returned:

C:\>(Get-ADUser -filter {SamAccountName -like "dron*"} |
     select SamAccountName | measure).count
1

 
In addition to the Measure-Object command-let that counts the number of objects, you can use the “tee” command that lets you store the result set into a variable and its number of elements into another. All of this in one single line:
 

C:\>$accountnb = (Get-ADUser -filter {SamAccountName -like "dr*"} |
                 select SamAccountName |
                 tee -Variable accounts | measure).count

C:\>$accountnb
3

C:\>$accounts

SamAccountName
--------------
draguene
drondy
droze

No responses yet

Trackback URI | Comments RSS

Leave a Reply