Count the Length of Array in PowerShell

Rohan Timalsina Dec 21, 2022 Apr 20, 2022
  1. Use the Length Property to Count the Length of Array in PowerShell
  2. Use the Count Property to Count the Length of Array in PowerShell
Count the Length of Array in PowerShell

An array is a data structure storing a collection of items, which can be the same or different types.

You can assign an array by assigning multiple values to a variable. Its items can be accessed using an index number in brackets [].

Sometimes, you might need to know how many items are stored in a PowerShell array. This tutorial will teach you to count the length of an array in PowerShell.

Use the Length Property to Count the Length of Array in PowerShell

You can use the Length property to determine how many items are stored in an array.

First, let’s create an array and assign values to it.

$array = "apple","ball","cat"
$array.GetType()

Output:

IsPublic    IsSerial      Name        BaseType
--------    --------      ----        --------
True          True      Object[]    System.Array

Let’s use the Length property to count the $array length.

$array.Length

Output:

3

As you can see, it printed the accurate length of an array.

Now, let’s create a single item array. You must use the comma (,) operator or array subexpression syntax.

Syntax of comma operator:

$data = ,"apple"

Syntax of array subexpression:

$data = @("apple")

The array items are placed in the @() parentheses. An empty array will be created when no values are set in ().

Now, let’s use the Length property.

$data.Length

Output:

1

If there are more than 2,147,483,647 elements in an array, the LongLength property is handy.

Use the Count Property to Count the Length of Array in PowerShell

Moreover, Count is an alias for the Length property. You can also use Count to find the length of an array.

$data.Count

Output:

1

It is easy to find the number of items stored in an array in PowerShell. We hope this article helped you understand how to count the length of an array in PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Array