Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 271
Barry Chum Avatar asked Sep 18 '12 13:09

Barry Chum


People also ask

How do you access array elements in PowerShell?

To access items in a multidimensional array, separate the indexes using a comma ( , ) within a single set of brackets ( [] ). The output shows that $c is a 1-dimensional array containing the items from $a and $b in row-major order.

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

How do I get the first element of an array in PowerShell?

Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].

How do you return an array in PowerShell?

First, use the array sub-expression operator @( ... ). This operator returns the result of one or more statements as an array. If there is only one item, the array has only one member. Use Write-Output with the switch -NoEnumerate to prevent PowerShell from un-rolling the array.


2 Answers

You can use the Range operator to slice the array:

$b = $a[1..2]
like image 192
Shay Levy Avatar answered Sep 23 '22 18:09

Shay Levy


It is worth noting the Range operator supports dynamic values - very useful when you want to work out your range dynamically, 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
like image 42
Emil Avatar answered Sep 19 '22 18:09

Emil