Count is a property on arrays

PS> $x = 1..10
PS> $x.Count

The same information is available through Length (which is the property in the System.Array class definition)

PS> $x.Length

If the variable is a scalar you get 1 returned

PS> $x = 1
PS> $x.Count

With an empty array you get zero returned

PS> $x = @()
PS> $x.Count

This means that however many items are in the array you can safely check the number of items.

Be careful with strings as Count and Length give different results

PS> $x = ‘asdfghjkl;’
PS> $x.count
PS> $x.length

If you want to test  the number of elements returned use Count rather than length

This entry was posted in Powershell. Bookmark the permalink.

1 Response to Count

  1. sau001 says:

    Very informative. I have always got confused with “Length” and “Count”. If “Length” is implemented by System.Array then who is responsible for “Count” ?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s