首页 > 解决方案 > Powershell中数组成员的统计分析

问题描述

[数组]$a=foreach($l in $l){xxxx}

$a 输出:</p>

@{D=xxx;p=x;pc=xxx;d=a;t=0-1} @{D=xxx;p=x;pc=xxx;d=b;t=0-1} @{D=xxx;p=x;pc=xxx;d=b;t=0-1} @{D=xxx;p=x;pc=xxx;d=a;t=1-2}
@{D=xxx;p=x;pc=xxx;d=c;t=1-2} @{D=xxx;p=x;pc=xxx;d=a;t=1-2}
......

$a[0] 输出:

@{D=xxx;p=x;pc=xxx;d=a;t=0-1}

我想要的是当 t 相同时 d 的出现次数。并将次数放入每个值中。

转换为 JSON 后

我要什么:</p>

{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"a",
"t":"0-1",
"Number":"1"},
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"b",
"t":"0-1",
"Number":"2"},
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"a",
"t":"1-2",
"Number":"2"},
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"c",
"t":"1-2",
"Number":"1"}

标签: arrayspowershell

解决方案


所以这里再次基本上是相同的答案,但现在,完全不针对您的真正问题。

# recreate the array of objects (renamed d to d2 - cannot have duplicate property names
$a = @(
    [pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'a'; t = '0-1' }
    [pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'b'; t = '0-1' }
    [pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'b'; t = '0-1' }
    [pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'a'; t = '1-2' }
    [pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'c'; t = '1-2' }
    [pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'a'; t = '1-2' }
)

# use group-object to group the objects by properties d2 and t
# get the count of the group and add it to first item in the group
# then output one item per group with the new count property
# last, pipe to ConvertTo-Json to create the json
$a | Group-Object d2, t |
    ForEach-Object {
        $item = $_.Group[0]
        $item | Add-Member -NotePropertyName 'Number' -NotePropertyValue $_.Group.Count
        $item
    } | ConvertTo-Json

输出

[
    {
        "D":  "xxx",
        "p":  "x",
        "pc":  "xxx",
        "d2":  "a",
        "t":  "0-1",
        "Number":  1
    },
    {
        "D":  "xxx",
        "p":  "x",
        "pc":  "xxx",
        "d2":  "b",
        "t":  "0-1",
        "Number":  2
    },
    {
        "D":  "xxx",
        "p":  "x",
        "pc":  "xxx",
        "d2":  "a",
        "t":  "1-2",
        "Number":  2
    },
    {
        "D":  "xxx",
        "p":  "x",
        "pc":  "xxx",
        "d2":  "c",
        "t":  "1-2",
        "Number":  1
    }
]

推荐阅读