Array Count property in PowerShell with pscustomobjects

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

If only strings are used, 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 there $objs.Count

isnull

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

    $Objects
}

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

      

Output: "Count: 2"

The behavior is different if I add lines

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

    $Objects
}

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

      

Output: "Count: 1"

+3


source to share


1 answer


You can force the function to return an array even if the nested array is built from a single object.

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

      

This comma makes an explicit conversion to an array, even if the supplied one is $Objects

already an array of multiple objects. This forces you to build an array with one element. Outside, Powershell makes unboxing a single element array, so you get the array if there is one, so this method works by default by Powershell to work with single-named arrays. You are experiencing Count

as 1 because in Powershell 3.0 Microsoft corrected single element arrays by adding a property Count

to each object
so that indexing one object returns Count

as 1 and for one $null

returns zero, but is excluded from it PSCustomObject

as a natural reason, states that they can contain your own propertiesCount

so the default property is Count

included for the custom object. This is why you don't get Count

if there is only one object.

The behavior ,

can be seen in 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

+3


source







All Articles