David.Chu.ca
David.Chu.ca

Reputation: 38654

Powershell: Output collection of objects

I have a collection of objects with properties:

$col = @{....}

and the data is something like this:

id     name     items
---    ----     -----
01     a        (a, b, c, d)
02     ....

items are array of strings. If I output the content of $col, the data are displayed as above. Is there any way to output values like this?

id     name     items
---    ----     -----
01     a        a
                b
                c
                d
02     b         
03     c        c1
04     d        d1
                d2
05 ...

Updated, the items column may contain empty, one or more than one items.

Upvotes: 4

Views: 6035

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 28993

First I setup something which is approximately your object, to test with:

$col = @(

    (New-Object –TypeName PSObject –Prop @{'id'='01';'name'='a';'items'=@(1,2,3)}),
    (New-Object –TypeName PSObject –Prop @{'id'='02';'name'='b';'items'=@(1,2,3)}),
    (New-Object –TypeName PSObject –Prop @{'id'='03';'name'='c';'items'=@(1,2,3)})
    )

Then print it:

$col

name id items    
---- -- -----    
a    01 {1, 2, 3}
b    02 {1, 2, 3}
c    03 {1, 2, 3}

Then define a custom format rule for the 'Items' column, which joins the collection items together using the newline character:

$itemFormat = @{Expression={($_.items -join "`n")};Label="Items";width=6}

Then print the collection with Format-Table, using -Wrap to allow it to wrap the long lines:

$col | Format-Table id,name,$itemFormat -Wrap -AutoSize

Which gives:

id name Items
-- ---- ------
01 a    1     
        2     
        3     
02 b    1     
        2     
        3     
03 c    1     
        2     
        3     

Upvotes: 7

Related Questions