Barry Chum Barry Chum - 3 months ago 9
PowerShell Question

Extract a range of array in Powershell

Assume there is an array in variable $a that is created like this,

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


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

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


I can use a simple for loop to do the task, but I am thinking if there is a more 'elegant' way to do this... may be a one-liner?

Thanks in advance.

Answer

You can use the Range operator to slice the array:

$b = $a[1..2]