Nerden
Nerden

Reputation: 41

outputting an array with overlapping fields

Good afternoon, I am having a little trouble outputting a powershell custom object.

Its an array showing people and what fruit they have (the information is collected through a number of other processes and would be a real PITA to change) eg;

First, last,<fruit>
Joe, Bloggs, apple=$true, banana=$true, pear=$true
Fred, Smith, apple=$true, melon=$true, banana=$true
Mick, Jones, pear=$true, melon=$true

If I use $array | fl * everything looks fine:

First: Joe
Last: Bloggs
apple: True
Banana: True
Pear: True

First: Mick
Last: Jones
apple: True
melon: True
banana: True

First: Fred
Last: Smith
Pear: True
melon: True

unfortunately when using out-gridview or export-csv or $array|ft * for that matter it only shows fields which are common across all records eg

$array|ft *
First     Last
----      ----
Joe       Bloggs
Mick      Jones
Fred      Smith

What I would like it do to is show all the combinations but just miss out the ones that don't exist,

$array|ft *
First     Last     Apple     Banana     Pear     Melon
----      ----     ----      ----       ----     ----
Joe       Bloggs   True      True       True
Mick      Jones    True      True                True
Fred      Smith                         True     True

(The easiest way would just be to join each fruit on to a Fruit" key/value for each record/person like

First: Joe
Last: Bloggs
Fruit: {apple, banana, melon}

"but that wouldn't work quite so well for the end goal)

Thanks in advance.

Upvotes: 0

Views: 41

Answers (1)

woxxom
woxxom

Reputation: 73586

Format-Table uses the first element's property list, so you'll need to manually build the list of all properties that exist in the array:

$fruits = $array | ForEach { $_.PSObject.Properties.Name -ne 'First' -ne 'Last' } |
                   Sort -unique
$properties = @('First', 'Last') + $fruits
$array | ft $properties

(The above code is for PS3.0+, so in PS2.0 use ($_.PSObject.Properties | Select -expand Name) instead of $_.PSObject.Properties.Name)

Or fix the first element so that Format-Table / Export-Csv / ConvertTo-Csv work correctly as is:

$missing = @{}
$array | ForEach { $_.PSObject.Properties | Select -expand Name } |
         Sort -Unique |
         Where { $array[0].$_ -eq $null } |
         ForEach { $missing.$_ = $null }
$array[0] | Add-Member -NotePropertyMembers $missing

Now the cmdlets will output all properties:

  • $array | ft

    First Last   apple Banana Pear melon
    ----- ----   ----- ------ ---- -----
    Joe   Bloggs  True   True True      
    Mick  Jones   True   True      True 
    Fred  Smith               True True 
    
  • $array | ConvertTo-Csv -NoTypeInformation

    "First","Last","apple","Banana","Pear","melon"
    "Joe","Bloggs","True","True","True",
    "Mick","Jones","True","True",,"True"
    "Fred","Smith",,,"True","True"
    

Upvotes: 1

Related Questions