Jonathan Rioux
Jonathan Rioux

Reputation: 1096

Get PSObject array size or count

I create an array like this:

$Array = @()

$Item = New-Object PSObject
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
$Item | Add-Member -Type NoteProperty -Name item2 -Value test

$Array += $Item

Now I want to add a check to determine if $Item is empty before adding it in $Array. How can I get the member count of $Item ?

I tried stuff like :

$Item.count
$Item.length
@($Item).count
($Item | Measure).count
($Item | Get-Member).count
$Item.psobject.members.count

But none of them gives me the actual member count.

Upvotes: 4

Views: 9895

Answers (3)

JosefZ
JosefZ

Reputation: 30123

The following Get_ItemCount function could help:

Function Get_ItemCount {
    $aux = $($item | Get-Member -MemberType NoteProperty)
    if ( $aux -eq $null ) {
        0
    } elseif ( $aux -is [PSCustomObject] ) {
        1
    } else {
        $aux.Count
    }
}

$Item = New-Object PSObject
Get_ItemCount                  # 0
$Item | Add-Member -Type NoteProperty -Name item1 -Value test
Get_ItemCount                  # 1
$Item | Add-Member -Type NoteProperty -Name item2 -Value test
Get_ItemCount                  # 2

Output

PS D:\PShell> .\SO\55064810.ps1
0
1
2
PS D:\PShell>

Upvotes: 1

user6811411
user6811411

Reputation:

You can use the hidden .PsObject.Properties to either check for

$Item.PSobject.Properties.Value.count or
$Item.PSobject.Properties.Names.count

$Item = New-Object PSObject
$Item.Psobject.Properties.value.count
0

$Item | Add-Member -Type NoteProperty -Name item1 -Value test
$Item.Psobject.Properties.value.count
1

$Item | Add-Member -Type NoteProperty -Name item2 -Value test
$Item.Psobject.Properties.value.count
2

Upvotes: 8

Jonathan Rioux
Jonathan Rioux

Reputation: 1096

The correct way is:

($Item|Get-Member -Type NoteProperty).count

Upvotes: 3

Related Questions