I have a PS custom object that is in this format:
|Name|Number|Email|
|----|------| -----|
|Bob| 23| [email protected]|
|Tom|124|[email protected]|
|Jeff|125|[email protected]|
|Jeff|127|[email protected]|
|Jeff|129|[email protected]|
|Jessica|126|[email protected]|
|Jessica|132|[email protected]|
I'd like to group together the fields where the numbers are the same. I.e:
|Name|Number|Email|
|----|------|-----|
|Bob|123|[email protected]|
|Tom|124|[email protected]|
|Jeff|125,127,129|[email protected]|
|Jessica|126,132|[email protected]|
I've tried a number of compare-object, sort-object, creating a new array etc. but I can't seem to get it.
Any ideas?
CodePudding user response:
Group-Object
is perfectly suited for that task. With the help of calculated properties, you can create a select statement that will produce the desired output in one sweep.
$data = @'
Name|Number|Email|
Bob| 23| [email protected]|
Tom|124|[email protected]|
Jeff|125|[email protected]|
Jeff|127|[email protected]|
Jeff|129|[email protected]|
Jessica|126|[email protected]|
Jessica|132|[email protected]|
'@ | ConvertFrom-Csv -Delimiter '|'
# Group by name and email
$data | Group-Object -Property Name, Email |
Select @{'Name' = 'Name' ; 'Expression' = { $_.Group[0].Name } },
@{'Name' = 'Number' ; 'Expression' = { $_.Group.Number } },
@{'Name' = 'Email' ; 'Expression' = { $_.Group[0].Email } }
Output
Name Number Email
---- ------ -----
Bob 23 [email protected]
Tom 124 [email protected]
Jeff {125, 127, 129} [email protected]
Jessica {126, 132} [email protected]
References