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.
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 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.
Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].
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.
You can use the Range operator to slice the array:
$b = $a[1..2]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With