Count

Count is a property on arrays

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

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

PS> $x.Length
10

If the variable is a scalar you get 1 returned

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

With an empty array you get zero returned

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

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
1
PS> $x.length
10

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

Advertisements
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” ?

    Thanks.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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