Beginner PowerShell Tip - The .Count Property Doesn't Exist If A Command Only Returns One Item

If you’re just getting started in PowerShell, it’s possible that you haven’t bumped into this specific issue yet. Perhaps you’ve got a variable $users and you’re assigning it a value like this.

PS> $users = Get-ADUser -Filter "samaccountname -like '*thmsrynr'"

This will get all the users in your Active Directory whose username ends with “thmsrynr”.

Great! Now how many users got returned? We can check the Count property to find out.

PS> $users.Count
3

Looks like there are three users in my AD that got returned. Now the problem at hand, what if there’s only one user returned? What if only one user in my AD has that kind of username? I’ll end up with this.

PS> $users.Count
# Nothing gets returned...

Even though I can do this and see there is one user in there.

PS> $users

DistinguishedName : CN=ThmsRynr,OU=Users,DC=PCLINC,DC=domain,DC=tld
Enabled           : True
GivenName         : Thomas
Name              : Thomas Rayner
ObjectClass       : user
ObjectGUID        : <snip>
SamAccountName    : ThmsRynr
SID               : <snip>
Surname           : Rayner
UserPrincipalName : thmsrynr@outlook.com

What if I was doing something like this?

if ($users.Count -gt 0) {
    # Do something
}
else {
    # Do something else
}

Since $users.Count is null even when there’s one user in there, my if statement won’t work correctly. Well, you can take a bit of a shortcut and do something a bit different when you’re assigning a value to $users.

$users = @(Get-AdUser -Filter "samaccountname -like '*thmsrynr'")

By wrapping the command in @( ) we are forcing $users to be an array even if only one item is returned.

This issue happens because PowerShell loves to unroll arrays and other collections for you. By doing this workaround, if there’s only one AD user whose username ends in thmsrynr, you’ll still end up with an array with a single item in it, and $users.Count will return “1” like you expected.

Written on December 6, 2017