4

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.

1
  • I know this question was already answered but I thought I would offer my answer from this thread as an alternative since I think it is a little more versatile. Commented Mar 31, 2014 at 16:22

1 Answer 1

7

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     
Sign up to request clarification or add additional context in comments.

3 Comments

I am trying your solution now. One thing I realize is that items may contain empty or only one item such as "1". In this case, the join would not work. My question is a simplified one. Any way to handle items with empty, one or array of string values?
I have updated my question with more example of column items.
@David.Chu.ca I would try changing the format Expression to be @($_.items) -join which will force it into an array. I think this will work for empty, single and multiple values in 'items'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.