Arrays and Lists

Array Definitions

PowerShell arrays hold lists of data. To define an array, use a comma to separate its elements:

$mySimpleArray = 1,"Two",3.14

Arrays may optionally be only a single element long:

$myWord = "Hello"

$myWord.Length shows a length of 5.

$myList = ,"Hello"

$myList.Length shows a length of 1.

The elements do not need to be all of the same datatype, unless you declare it as a strongly typed array. The outer square brackets define a strongly typed variable (as mentioned in the section named “Variables”), and 'int[]' (for example) represents an array of integers:

[int[]] $myArray = 1,2,3.14

In this mode, PowerShell throws an error if it cannot convert any of the elements in your list to the required datatype.

Arrays can also be multi-dimensional—arrays within arrays:

$multiDimensional = @(
      (1,2,3,4),
      (5,6,7,8)
 )

$multiDimensional[0][1] returns 2, coming from row 0, column 1.

$multiDimensional[1][3] returns 8, coming from row 1, column 3.

Array Access

To access a specific element in an array, use the '[]' operator. PowerShell numbers your array elements starting at zero:

$myArray[0]

Returns 1, the first element in the array.

$myArray[2]

Returns 3, the third element in the array.

$myArray[-1]

Returns the last element of the array.

$myArray[-2]

Returns the second-to-last ...

Get Windows PowerShell Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.