0

I have two collections and object in it. when display both collections it just display one. please advice

Function Test{
 $Table1 = New-Object 'System.Collections.Generic.List[System.Object]'

 $Table2 = New-Object 'System.Collections.Generic.List[System.Object]'

 $obj = [PSCustomObject]@{
'Name'    = 'Jack'
'Age' = '21'
 }
 $Table1.Add($obj)

  $obj2 = [PSCustomObject]@{
'Name'    = 'Jack'
'city' = 'BKG'
 }
 $Table2.Add($obj2)

 $Table1
 $Table2

 }
 Test
output is:
Name Age
---- ---
Jack 21 
Jack    

i want the output as below

Name Age
---- ---
Jack 21 

Name city
---- ----
Jack BKG 

please advice

1 Answers1

2

When you send multiple objects from an array or function to the console it will determine what properties are shown in a table from the first object it receives. Typically objects received from a function or array are similar objects with similar properties so this works.

In your case you are sending 2 objects with different properties so you are getting this unwanted behavior of only seeing the properties from the first object. This does not mean that the city property does not exist on the 2nd object or that the 2nd object has an age property.

If you want to include the properties from the 2nd object you have to force them to be shown

test | Format-Table *, city

or

test | Format-Table name, age, city

in which case you see the following

Name Age city
---- --- ----
Jack 21
Jack     BKG

Not exactly what you were looking for, but still you can at least see the city property now. You may also use Format-List without specifying the property names because in this format each object can be individually listed with each of their actual properties.

test | Format-List                 

Name : Jack
Age  : 21

Name : Jack
city : BKG

If you want both object in table view but separate tables like you show above you can use a foreach loop and send each individually to Format-Table or Out-Host like so

Test | ForEach-Object { $_ | Out-Host }

Name Age
---- ---
Jack 21


Name city
---- ----
Jack BKG

Each object was sent solo allowing Out-Host to evaluate and include each object's properties in table format

Daniel
  • 4,792
  • 2
  • 7
  • 20