Powershell count groups of items based on substring

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:

Data example:

I’d like the script to give me something like the following:

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:

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:






Edit using Group-Object -NoElement would have left only the reordering for the last step

Source:

Powershell count groups of items based on substring by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply