PowerShell : Arrays

PowerShell provides a data structure, An array, that is designed to store a collection of items. The items can be the same type or different types.

To create and initialize an array, just assign multiple values to a variable with a comma separated.

PS > $my_array = 5,7,13,45

You can also use range operator (..) as below

PS  > $range_array = 2..8

As a result, $range_array contains six values: 2, 3, 4, 5, 6, 7, and 8.

When no data type is specified, PowerShell creates each array as an object array (type: System.Object[])

To determine the data type of an array, use the GetType() method.

PS > $my_array.GetType()

To cast an array, precede the variable name with an array type enclosed in brackets such as string[], long[], or int32 .

PS > [int32[]]$values = 1000,2000,3000,4000

As a result, the $values array can contain only integers.

Sub-expression operator

The array sub-expression operator creates an array, even if it contains zero or one object.

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

PS > $b = @("PowerShell Tutorial")
PS > $b.Count

To display all the elements in the array, type the array name

PS > $b

You can also refer to the elements in an array by using an index, beginning at position 0.

PS > $a[0]

You can retrieve part of the array using a range operator for the index.

PS > $a[1..4]

Negative numbers count from the end of the array. “-1” refers to the last element of the array.

PS > $a[-3..-1]