Format-Table -GroupBy在一行上显示数组属性

时间:2018-01-08 00:49:26

标签: powershell grouping formattable

我正在创建一个包含两个属性的自定义对象。第一个是字符串,基本上是一个键,第二个是返回数组的函数的输出。然后我将结果传递给Format-Table并按字符串属性进行分组。我希望看到的是数组属性的每个元素在输出中的单独行上。相反,Format-Table将数组显示在一行上。

是否有任何格式化输出的方法,以便数组属性的每个元素都显示在一个单独的行上?

以下是一些说明问题的代码:

function Get-Result([string]$lookup)
{
    if ($lookup -eq "first")
    {
        return @("one", "two")
    }
    else
    {
        return @("three")
    }
}

$a = "first", "second"

$a | 
    Select-Object @{Name="LookupValue"; Expression={$_}}, `
        @{Name="Result"; Expression={Get-Result $_}} | 
    Format-Table -GroupBy LookupValue

这就是它的输出:

   LookupValue: first

LookupValue Result    
----------- ------    
first       {one, two}


   LookupValue: second

LookupValue Result
----------- ------
second      three 

我希望看到的是:

   LookupValue: first

LookupValue Result    
----------- ------    
first       one  
first       two    


   LookupValue: second

LookupValue Result
----------- ------
second      three 

2 个答案:

答案 0 :(得分:2)

Format-cmdlets不会创建不存在的对象。您的示例具有包含数组的结果值。如果您不希望它是一个数组,而是两个不同对象的一部分,那么您需要以某种方式将其拆分出来更改您的创建过程以生成那些多个/缺少的对象。

前者通过添加另一个内部循环来处理多个"结果"

$a | ForEach-Object{
    $element = $_
    Get-Result $element | ForEach-Object{
        $_ | Select-Object @{Name="LookupValue"; Expression={$element}},
            @{Name="Result"; Expression={$_}}
    }
} | Format-Table -GroupBy LookupValue

因此,对于Get-Result的每个输出,都会创建一个新对象,引用由LookupValue表示的管道中的当前$element

这有点笨重所以我还想添加一个梯子的例子来改变你的创作过程

function Get-Result{
    param(
        [Parameter(
            ValueFromPipeline)]
        [string]$lookup
    )

    process{
        switch($lookup){
            "first"{
                [pscustomobject]@{LookupValue=$lookup;Result="one"},
                [pscustomobject]@{LookupValue=$lookup;Result="two"}
            }
            default{
                [pscustomobject]@{LookupValue=$lookup;Result="three"}
            }

        }
    }
}

$a = "first", "second"
$a | Get-Result | Format-Table -GroupBy LookupValue

创建一个接受管道输入的函数,并根据$lookup吐出pscustomobjects。我在这里使用了一个开关,以防你的实际应用比你在样品中显示的条件更多。

注意

为了-GroupBy工作,应该对数据集进行排序。因此,如果您遇到的问题是真实数据无法正确显示......请先排序。

答案 1 :(得分:1)

获得它的一种方法 -

function Get-Result([string]$lookup) {
    if ($lookup -eq "first") {
        Write-Output @( 
            @{ LookupValue=$lookup; Result="one" },
            @{ LookupValue=$lookup; Result="two" }
        )
    }
    else {
        Write-Output @(
            @{ LookupValue=$lookup; Result="three" }
        )
    }
}

"first", "second" | % {  Get-Result($_) } | % { [PSCustomObject]$_ } | Format-Table LookupValue, Result -GroupBy LookupValue

输出:

    LookupValue: first

LookupValue Result
----------- ------
first       one   
first       two   


   LookupValue: second

LookupValue Result
----------- ------
second      three