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.

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.

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.

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

What if I was doing something like this?

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.

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.

2 thoughts on “Beginner PowerShell Tip: The .Count Property Doesn’t Exist If A Command Only Returns One Item

    1. It’ll help you basically anywhere that you are expecting to be working with an array of objects, but you might only have received one. For instance, an array of lines in a file – what if there’s only one line? Etc.

Leave a Reply

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