3

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.

Jonathan Rioux
  • 1,067
  • 2
  • 14
  • 30
  • For future "dupe close" folk: This does looks a lot like [this previously asked question](https://stackoverflow.com/questions/53103213/how-do-i-get-the-length-of-a-pscustom-object/53103518), at least by title, but I'd say that one is more specifically about iteration and this one is clearly & nicely to the length/count point. I was going to edit that question's title to mention iteration, but thought that would be too heavy-handed. – ruffin Jan 20 '22 at 16:59

3 Answers3

7

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
  • 3
    Indeed (+1); it's strange that the collection returned fro `.properties` has no `.Count` or `.Length` property; a more concise alternative is `@($Item.psobject.properties).Count` – mklement0 Mar 08 '19 at 23:38
  • Oddly, this did not work for the result of an `Import-CSV` statement, which generates a `PSCustomObject`. I could not find any built-in `Count` or `Length`. I had to use this code: `$Obj.PSObject.Properties | Measure-Object | Select-Object -ExpandProperty "Count"` – Slogmeister Extraordinaire Jan 12 '21 at 15:45
2

The correct way is:

($Item|Get-Member -Type NoteProperty).count
Jonathan Rioux
  • 1,067
  • 2
  • 14
  • 30
1

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>
JosefZ
  • 28,460
  • 5
  • 44
  • 83