user2641103
user2641103

Reputation: 702

How to slice a two-dimensional array in PowerShell?

I have a two-dimensional array from a database query by using an ADODB connection. Briefly, after opening the connection I retrieve a recordset by:

$rs2 = New-Object -ComObject ADODB.Recordset

$sql = "<some SELECT statement here>"

$rs2.Open($sql, $conn)

$rows = $rs2.GetRows(1000)

I want to see just the first 10 rows for a particular column. So, I've tried:

$rows[0,(0..9)]

but it successfully fails giving the error:

You cannot index into a 2 dimensional array with index [0].
At line:1 char:1
+ $rows[0,(0..9)]
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NeedMultidimensionalIndex

The array has 1000 rows and over 200 columns. I can use the syntax:

$rows[0,100]

without problems.

What am I missing here?

Upvotes: 0

Views: 1993

Answers (2)

gvee
gvee

Reputation: 17161

Because you're using an ADODB.Recordset object, you have specific methods to access the data.

To get the value from the first row, first column:

$rows.GetValue(0,0)

first row, second column:

$rows.GetValue(1,0)

second row, sixth column:

$rows.GetValue(5,1)

etc.

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

The index operator accepts a list of values, but if your array has a dimension > 1 that list must be a list of arrays, so that each individual list element identifies one element of your original array.

$indexes = 0..9 | ForEach-Object { ,@(0, $_) }
$rows[$indexes]

The leading comma in ,@(0, $_) prevents PowerShell from unrolling the array @(0, $_) by wrapping it in another array that is unrolled instead.

Essentially you need to construct a list of tuples identifying the array elements you want to access, then use that list with the index operator.

$rows[0][0..9] doesn't work because you have a 2-dimensional array, not a jagged array (an array of arrays).

Upvotes: 4

Related Questions