Question:
I have an array of data gleaned from a command that contains several elements. Each item’s name element starts with a three or four character identifier followed by a hyphen. I would like to get a count of all items in the array that contains the same identifier.
Data gathered with the following PowerCLI (VMware) command:
1 2 |
$items = Get-Datastore |
Data example:
1 2 3 4 5 6 7 8 9 10 11 |
NAME STATUS INFO DETAIL ABC-1234-XXXX PoweredOn Info Detail ABC-1235-XXXX PoweredOn Info Detail ABC-1236-XXXX PoweredOn Info Detail BCA-1234-XXXX PoweredOn Info Detail BCA-1235-XXXX PoweredOn Info Detail CBA-1234-XXXX PoweredOn Info Detail CBA-1235-XXXX PoweredOn Info Detail CBA-1236-XXXX PoweredOn Info Detail CBA-1237-XXXX PoweredOn Info Detail |
I’d like the script to give me something like the following:
1 2 3 4 5 |
NAME COUNT ABC 3 BCA 2 CBA 4 |
I really don’t have a code example, but I’ve considered using the PowerShell “group” method in conjunction with the count method. I’m struggling with how to combine everything into something usable.
Group:
1 2 |
$array = $items | Group Name |
Count:
1 2 |
$array.count |
EDIT: Added data gathering command
Answer:
You are close, but you don’t want to group by the complete name – you want to split name
at – and take only the first [0] element.
This can be done on the fly
inside a {script block} as a calculated property. Here the group is the desired outcome, in other cases (sorting on an otherwise not existing property) it doesn’t leave traces in present data.
This shows stepwise the transformation of your data:
1 2 3 |
$items = Get-Datastore $Items |
1 2 3 4 5 6 7 8 9 10 11 12 |
NAME STATUS INFO DETAIL ---- ------ ---- ------ ABC-1234-XXXX PoweredOn Info Detail ABC-1235-XXXX PoweredOn Info Detail ABC-1236-XXXX PoweredOn Info Detail BCA-1234-XXXX PoweredOn Info Detail BCA-1235-XXXX PoweredOn Info Detail CBA-1234-XXXX PoweredOn Info Detail CBA-1234-XXXX PoweredOn Info Detail CBA-1234-XXXX PoweredOn Info Detail CBA-1234-XXXX PoweredOn Info Detail |
1 2 |
$Items | Group-Object {$_.Name.Split('-')[0]} |
1 2 3 4 5 6 |
Count Name Group ----- ---- ----- 3 ABC {@{NAME=ABC-1234-XXXX; STATUS=PoweredOn; INFO=Info; DETAIL=Detail}, ... 2 BCA {@{NAME=BCA-1234-XXXX; STATUS=PoweredOn; INFO=Info; DETAIL=Detail}, ... 4 CBA {@{NAME=CBA-1234-XXXX; STATUS=PoweredOn; INFO=Info; DETAIL=Detail}, ... |
1 2 |
$Items | Group-Object {$_.Name.Split('-')[0]} | Select-Object Name,Count |
1 2 3 4 5 6 |
Name Count ---- ----- ABC 3 BCA 2 CBA 4 |
Edit using Group-Object -NoElement would have left only the reordering for the last step