Grouping object using two Properties

Hello Everyone,

I am starting to deep into powershell scripting, I have one task that is to get some stats of incoming and outgoing mails, this is not the problem, I manage to have the list in a result variable, but I need to group it and measure it by two properties in a hierarchical way.

This is an example of the list:

Route                                             To
--------                                       ----------

Outgoing                                      mail1@domain.com

Outgoing                                      mail2@domain.com

Incoming                                      mail1@domain.com

Incoming                                      mail3@domain.com

.....

These are the mentioned properties

Route: NoteProperty System.String
To: NoteProperty System.String

The final result should be sometime like this:

Route                                               To                                                        Count
--------                                         ----------                                                 ---------

Outgoing                                                                                                       3

mail1@domain.com                                   2

mail2@domain.com                                   1

Incoming                                                                                                       5

mail1@domain.com                                   1

mail3@domain.com                                   4

Any suggestion on how to archive this are welcome.

Thanks.

You can use Group-Object cmelet. You will do it against both the properties (Route and To). Can you attempt with this hint and let us know here if you face any difficulties.

The only way to really group this visually is with `Format-Table`, but this won’t get you a usable structured object to further process, so mind that you only do the formatting action when necessary, and retain the data as properly structured objects in a variable before that point, if you need to do any number crunching.

PS Z:\Scripts\> $MailItems | Sort-Object -Property Route | Format-Table -GroupBy Route


   Route: Incoming
Route    Mail
-----    ----
Incoming mail3@example.com
Incoming mail1@example.com

   Route: Outgoing
Route    Mail
-----    ----
Outgoing mail1@example.com
Outgoing mail2@example.com

There isn’t really a supported way to insert counts, however, but conceivably you could just print those on a line after the tables by doing:

$Incoming, $Outgoing = ($MailItems | Group-Object -Property Route).Where({$_.Name -eq 'Incoming'}, 'Split').Count
Write-Host "Total Incoming: $Incoming - Total Outgoing: $Outgoing"