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 element of the array. You can also access ranges of elements in your array:

$myArray[0..2]

Returns elements 0 through 2, inclusive.

$myArray[-1..2]

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.

$myArray[-1..-3]

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.

Array Slicing

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:

$myArray[0,2,4]

Returns elements 0, 2, and 4.

$myArray[0,2+4..6]

Returns elements 0, 2, and 4 through 6, inclusive.

$myArray[,0+2..3+0,0]

Returns elements 0, 2 through 3 inclusive, 0, and 0 again.

Tip

You can use the array slicing syntax to create arrays, as well:

$myArray = ,0+2..3+0,0
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.126.80