Result set is object for 1 record, array for many?

Question:

I can’t believe it, but all indications are that my PowerShell code is returning the result of a SELECT query that finds 1 record as an object, but if there are two or more records the same code returns an array of objects. What am I doing wrong?

Below is the code:

When $result is only 1 record, $result.Count returns nothing, and I can access the columns as $result.id and not $result[0].id. If there are 2 or more records returned the opposite is true.

Please tell me I’m doing something wrong, and that this is not the way PowerShell works.

Answer:

PowerShell returns results based on this simple algorithm:

  • More than one item –> return an array of those items
  • Just one item –> return the item

Often it is good practice to coerce PowerShell to always return an array, using either of these:

However, these operators are not identical! You can safely apply the @() grouping operator to anything to force array output–an array always has a Count property, for example:

The comma array construction operator, on the other hand, works like this:

…because it builds a nested array with whatever it is given.

Source:

Result set is object for 1 record, array for many? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply