'Count the number of variables containing objects

I have an issue with .count. Its to do with the way it counts objects and also arrays containing objects.

For dull reasons, I have a situation where I don't know if what is being passed into my function is a single array of objects or 2 or more variables holding array lists of objects.

I though it would be easy to detect this. But because of the way count tries to help me out I am having trouble. When 2 or more arrays of objects are returned count reflects the number of arrays. But when only one is return count reflects the amount of objects in that array.

Simplified demo using simple arrays:

$Arr1 = "a","b","c"
$Arr2 ="d","f","e"

$arrayjoined = $Arr1,$Arr2

#count showing the number of arrays = 2
$arrayjoined.count

# Count on just one array = 3
$Arr1.count

My original function works apart from occasions when only one array is returned. Is there any thing I can do to check for this, or force the count to return 1 to reflect just one array returned?

PS. I know I can use += to get the results into the same array in the example above but I can't do this with the arrays coming into my function.



Solution 1:[1]

So what can we do if we can to count arrays in a array

$Array = 1,2,3
$CountArray = $Array
$CountArray.Length
$CountArray.Count

Will return

3
3

We can instead prepend the array with a ,

$Array = 1,2,3
$CountArray = ,$Array
$CountArray.Length
$CountArray.Count

Which will return

1
1

You can also add to an array like this

$Array = @()
$Array += ,@(1,2,3)
$Array.Length
$Array.Count

Returns

1
1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ArcSet