如何从两个数组中分组数据并获取计数

时间:2017-05-24 19:56:51

标签: powershell powershell-v2.0 powershell-v3.0

如果我有两个数组,并且region列没有相同的值 像

$ DATA1 =

Region             Type 
    ------            -----------
    EuropeWest         Operational
    EuropeWest         Operational
    EuropeWest         Operational
    EuropeNorth        Operational
    USCentral          Operational
    USCentral          Operational
    AsiaEast           Operational
    AsiaEast           Operational
    AsiaEast           Operational

$ DATA2 =

Region             Type
------             -----------
EuropeWest         MigrateSource
EuropeWest         MigrateSource
EuropeNorth        MigrateSource
USCentral          MigrateSource
USEast             MigrateSource

输出应为:

    Region             Operational      MigrateSource
    ------             -----------      ----------- 
    EuropeWest          4                2
    EuropeNorth         1                1
    USCentral           2                0
    AsiaEast            3                1
   Useast               0                1

任何帮助都非常感激?

我能够对它进行分组但是在这里没有得到任何关于如何使用foreach循环的线索:

$data1 | group -Property region | select name,@{n='Operationaclcount';e={$_.count}}
$data2 | group -Property region | select name,@{n='Migratesourcecountt';e={$_.count}}

2 个答案:

答案 0 :(得分:0)

如果要组合两个数组,只需使用加号。像这样:

var validated_elements = $("p").filter(function() {
    var found = false;
    $.each($(this).data(function(key) {
        if (key.match(/^data-validation/)) {
            found = true;
            return false;
        }
    }
    return found;
});

答案 1 :(得分:0)

由于您有两个具有属性name的对象,如果我们将这些对象组合在一起,我们就会有一个完整的名称列表。使用ForEach循环,我们将循环遍历这些名称,并使用Where-Object过滤为计数创建的两个对象中的每一个。然后,我们将使用[pscustomobject]创建一个新对象。最后快速测试组中是否缺少名称,表示计数为零。

$OpCount = $data1 |
    Group-Object -Property region |
    Select-Object name,@{n='Operationalcount';e={$_.count}}
$MigCount = $data2 |
    Group-Object -Property region |
    Select-Object name,@{n='Migratesourcecount';e={$_.count}}
$CombinedNames = $OpCount.name + $MigCount.name
Foreach ($Name in $CombinedNames) {
    $entry = [pscustomobject]@{
        Operational = $OpCount |
            Where-Object {$_.name -eq $Name} |
            Select-Object -Expand Count
        MigrateSource = $MigCount |
            Where-Object {$_.name -eq $Name} |
            Select-Object -Expand Count
    }
    if ($entry.Operational -eq $null) { $entry.Operational = 0 }
    if ($entry.MigrateSource -eq $null) { $entry.MigrateSource = 0 }
    $entry
}