4

If the array has only one CustomObjects and the Count property is null. Why?

If use only strings, the Count property is one.

function MyFunction
{
    $Objects = @()
    $Objects += [pscustomobject]@{Label = "Hallo"}
    # $Objects += [pscustomobject]@{Label = "World"}

    $Objects
}

$objs = MyFunction
Write-Host "Count: $($objs.Count)"

Output: "Count: " because $objs.Count is null

function MyFunction
{
    $Objects = @()
    $Objects += [pscustomobject]@{Label = "Hallo"}
    $Objects += [pscustomobject]@{Label = "World"}

    $Objects
}

$objs = MyFunction
Write-Host "Count: $($objs.Count)"

Output: "Count: 2"

Behavior is different if I add strings

function MyFunction
{
    $Objects = @()
    $Objects += "Hallo"
    # $Objects += [pscustomobject]@{Label = "World"}

    $Objects
}

$objs = MyFunction
Write-Host "Count: $($objs.Count)"

Output: "Count: 1"

hdev
  • 6,097
  • 1
  • 45
  • 62

1 Answers1

4

You can force the function to return an array even if the nested array is constructed of one object.

function MyFunction
{
    $Objects = @()
    $Objects += [pscustomobject]@{Label = "Hallo"}
    # $Objects += [pscustomobject]@{Label = "World"}
    return ,$Objects
}

That comma makes an explicit conversion to an array even if the supplied $Objects is already an array of more than one object. This forces a construction of an array with one element. Outside, Powershell does unboxing of a one-item array, so you'll get an array if there was one, so this method works around default Powershell behavior for working with one-item arrays. You experience Count being 1 because in Powershell 3.0 Microsoft fixed one-item arrays by adding Count property to every object so that indexing of one object returns Count as 1, and for $null zero is returned, but the PSCustomObjects are excluded from this as a natural reason declares that they can contain their own Count properties, thus no default Count property is included for a custom object. That's why you don't get Count if there's only one object.

The behavior of , can be seen on the following example:

function hehe {
    $a=@()
    $a+=2
    $a+=4
    $b=,$a
    write-verbose $b.count # if a variable is assigned ",$a", the value is always 1
    return ,$a
}

Output:

PS K:> (hehe).count

VERBOSE: 1

2

Community
  • 1
  • 1
Vesper
  • 18,599
  • 6
  • 39
  • 61