Selecting elements from an array

Individual elements from an array may be selected using an index. The index counts from 0 to the end of the array. The first and second elements are available using index, 0 and 1:

$myArray = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 
$myArray[0] 
$myArray[1] 

In a similar manner, array elements can be accessed counting backward, from the end. The last element is available using the -1 index, and the penultimate element using the -2 index, for example:

$myArray[-1] 
$myArray[-2] 

Ranges of elements may be selected either going forward (starting from 0) or going backward (starting with -1):

$myArray[2..4] 
$myArray[-1..-5] 

More than one range can be selected in a single statement:

$myArray[0..2 + 6..8 + -1] 

This requires some care. The first part of the index set must be an array for the addition operation to succeed. The expression in square brackets is evaluated first and converted into a single array (of indexes) before any elements are selected from the array:

PS> $myArray[0 + 6..8 + -1]
Method invocation failed because [System.Object[]] does not contain a method named 'op_Addition'.
At line:1 char:1
+ $myArray[0 + 6..8 + -1]
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

Exactly the same error would be shown when running the expression within square brackets alone:

0..2 + 6..8 + -1 

The following modified command shows two different ways to achieve the intended result:

$myArray[@(0) + 6..8 + -1] 
$myArray[0..0 + 6..8 + -1] 
..................Content has been hidden....................

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