Powershell:输出对象集合

Dav*_*.ca 3 powershell

我有一组具有属性的对象:

$col = @{....}
Run Code Online (Sandbox Code Playgroud)

而数据是这样的:

id     name     items
---    ----     -----
01     a        (a, b, c, d)
02     ....
Run Code Online (Sandbox Code Playgroud)

items是字符串数组.如果我输出$ col的内容,则数据显示如上.有没有办法输出这样的值?

id     name     items
---    ----     -----
01     a        a
                b
                c
                d
02     b         
03     c        c1
04     d        d1
                d2
05 ...
Run Code Online (Sandbox Code Playgroud)

更新后,items列可能包含空,一个或多个项.

Tes*_*ler 5

首先,我设置一些近似于你的对象的东西,用以下方法测试:

$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)})
    )
Run Code Online (Sandbox Code Playgroud)

然后打印出来:

$col

name id items    
---- -- -----    
a    01 {1, 2, 3}
b    02 {1, 2, 3}
c    03 {1, 2, 3}
Run Code Online (Sandbox Code Playgroud)

然后为"Items"列定义自定义格式规则,该列使用换行符将集合项连接在一起:

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

然后使用Format-Table打印集合,使用-Wrap它来包装长行:

$col | Format-Table id,name,$itemFormat -Wrap -AutoSize
Run Code Online (Sandbox Code Playgroud)

这使:

id name Items
-- ---- ------
01 a    1     
        2     
        3     
02 b    1     
        2     
        3     
03 c    1     
        2     
        3     
Run Code Online (Sandbox Code Playgroud)