计算数组中数据的出现次数

时间:2016-03-31 12:36:44

标签: arrays powershell

我有一个这样的数组:

OptiPlex 790
Precision WorkStation T7500
Precision WorkStation T7400
Precision T1500
Precision WorkStation T3500
CELSIUS R650
VMware Virtual Platform
Precision T1500
OptiPlex GX620

我想得到数组的数量,并将其添加到新数组中。

Element:Count
OptiPlex 790 1 
Precision WorkStation T7500 1 
Precision WorkStation T7500 1

我想将此值存储在新数组中。所以,我将在以后/其他地方使用它。

$array = @()
for ($i=1; $i -le $rowMax-1; $i++) {
    $Model = $sheet.Cells.Item($rowModel+$i, $colModel).text
    Write-Host ("I am reading data on row: " + $i)
    $array += $Model
}

$array | Group

目前上面的脚本工作正常,但我不知道如何将这些数据添加到新数组中。

2 个答案:

答案 0 :(得分:2)

您可以使用Group-Object cmdlet:

$array | group | select Name, Count

输出:

Name                        Count
----                        -----
OptiPlex 790                    1
Precision WorkStation T7500     1
Precision WorkStation T7400     1
Precision T1500                 2
Precision WorkStation T3500     1
CELSIUS R650                    1
VMware Virtual Platform         1

答案 1 :(得分:1)

我会构造一个哈希表而不是一个数组:

$Models = @(
  'OptiPlex 790'
  'Precision WorkStation T7500'
  'Precision WorkStation T7400'
  'Precision T1500'
  'Precision WorkStation T3500'
  'CELSIUS R650'
  'VMware Virtual Platform'
  'Precision T1500'
  'OptiPlex GX620'
)

# Create a hashtable
$ModelCount = @{}

# Iterate over each entry in the array, increment value count in hashtable
$Models |ForEach-Object { $ModelCount[$_]++ }

现在您的哈希表会计算您需要的所有信息:

PS C:\> $ModelCount

Name                           Value
----                           -----
OptiPlex 790                   1
VMware Virtual Platform        1
Precision WorkStation T7500    1
Precision T1500                2
CELSIUS R650                   1
Precision WorkStation T7400    1
OptiPlex GX620                 1
Precision WorkStation T3500    1

您可以轻松添加新值:

# Let's say you found another 3 OptiPlex GX620 somewhere:
$ModelCount['OptiPlex GX620'] += 3

和条目:

$ModelCount['New Model']++

你仍然可以迭代它:

PS C:\> $ModelCount.Keys |Sort-Object |ForEach-Object {
>>>     Write-Host "We have $($ModelCount[$_]) of $_ in stock"
>>> }
We have 1 of CELSIUS R650 in stock
We have 1 of OptiPlex 790 in stock
We have 4 of OptiPlex GX620 in stock
We have 2 of Precision T1500 in stock
We have 1 of Precision WorkStation T3500 in stock
We have 1 of Precision WorkStation T7400 in stock
We have 1 of Precision WorkStation T7500 in stock
We have 1 of VMware Virtual Platform in stock