PowerShell arrays hold lists of data. To define an array, use a comma to separate its elements:
Arrays may optionally be only a single element long:
$myWord.Length
shows a length
of 5.
$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:
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[0][1]
returns 2, coming from row 0, column 1.
$multiDimensional[1][3]
returns 8, coming from row 1, column 3.
To access a specific element in an array, use the '[]'
operator. PowerShell numbers your array
elements starting at zero:
Returns 1, the first element in the array.
Returns 3, the third element in the array.
Returns the last element of the array.
Returns the second-to-last element of the array. You can also access ranges of elements in your array:
Returns elements 0 through 2, inclusive.
Returns the final element, wraps around, and returns elements 0 through 2, inclusive. PowerShell wraps around because the second number in the range is positive.
Returns the last element of the array through to the third-to-last element in array, in decreasing order. PowerShell scans backward because the second number in the range is negative.
You can combine several of the above statements at once to
extract more complex ranges from an array. Use the +
sign to separate array ranges from
explicit indexes:
Returns elements 0, 2, and 4.
Returns elements 0, 2, and 4 through 6, inclusive.
Returns elements 0, 2 through 3 inclusive, 0, and 0 again.
18.119.126.80