I have an array like this:
OptiPlex 790 Precision WorkStation T7500 Precision WorkStation T7400 Precision T1500 Precision WorkStation T3500 CELSIUS R650 VMware Vir
I would construct a hash table rather than an array:
$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[$_]++ }
Now your hash table countains all the information you need:
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
And you can easily add new values:
# Let's say you found another 3 OptiPlex GX620 somewhere:
$ModelCount['OptiPlex GX620'] += 3
and entries:
$ModelCount['New Model']++
And you can still iterate over it:
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
There is a Group-Object cmdlet which you can use for that:
$array | group | select Name, Count
Output:
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