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"

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

As a note, a single pscustomobject has a count of 1 in PS 7.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.