Powershell 如何将两个数组中的数据分组并获取计数
若我有两个数组,并且区域列并没有相同的值 像 $data1=Powershell 如何将两个数组中的数据分组并获取计数,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,若我有两个数组,并且区域列并没有相同的值 像 $data1= Region Type ------ ----------- EuropeWest Operational EuropeWest Operational EuropeWest Operational EuropeNorth Operational USCentral
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}}
如果要组合两个阵列,只需使用加号。大概是这样的:
$data1 + $data2 | Group-Object region | % {
New-Object psobject -property @{
Name = $_.Name
Operational = $_.Count
MigrateSource = @($_.Group | Select Type -Unique).Count
}
}
由于有两个对象具有一个属性
名称
,如果我们将它们组合在一起,则会得到完整的名称列表。使用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
}
你能展示一下你迄今为止所做的尝试吗?你在哪里遇到问题?起始点是
Group Object
,一个ForEach
loopI能够对它进行分组,但是没有得到任何关于如何在这里使用ForEach循环$data1 | Group-Property region | select name,@{n='Operationaclcount';e={$.count}$data2 | Group-Property region | select name,@{n='migrateSourceCount e'{.count如何获取同一对象中的migratesource计数?已修改migratesource的答案。不确定如何在示例中获得USCentral=0。