Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Output collection of objects

Tags:

powershell

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.

like image 279
David.Chu.ca Avatar asked Oct 16 '25 10:10

David.Chu.ca


1 Answers

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     
like image 82
TessellatingHeckler Avatar answered Oct 19 '25 07:10

TessellatingHeckler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!