Extract array range in Powershell

Suppose there is an array in the variable $ a, which is created in such a way

$a = ,@(1,2,3) $a += ,@(4,5,6) $a += ,@(7,8,9) $a += ,@(10,11,12) 

I want to extract part of an array, for example $ a [1] and $ a [2], into another variable, for example $ b such that

 $b[0] = @(4,5,6) $b[1] = @(7,8,9) 

I can use a simple loop to complete the task, but I think that if there is a more β€œelegant” way to do this ... maybe one-line?

Thanks in advance.

+8
arrays loops powershell
source share
2 answers

You can use the Range operator to slice an array:

 $b = $a[1..2] 
+12
source share

It is worth noting that the Range operator supports dynamic values ​​- it is very useful when you want to dynamically change your range, for example:

 $a = @(0,1,2,3,7) $b = @(4,5,6) $twotoseven = $a[($a.Length-($a.Length-2))..($a.Length-2)] + $b + $a[-1] 

Output:

 2 3 4 5 6 7 
0
source share

All Articles