Reputation: 23
I am just getting started with PowerShell and can not find an answer to this anywhere.
Trying to write a script that imports a CSV file and searches through the file to see if any names are the same. If the names are the same I want to write all of those values together on the same line and only show the name once.
For example:
Name Number
Tom 1
Tom 4
Bill 3
Dave 2
Dave 5
Dave 6
With this output:
Tom- The number(s) associated with this person is/are: 1/4
Bill- The number(s) associated with this person is/are: 3
Dave- The number(s) associated with this person is/are: 2/5/6
Upvotes: 2
Views: 2223
Reputation: 387
less elegant version
$Data = Import-Csv .\test.csv
$hash = @{}
$output = @()
foreach ($name in $data) {
$hash[$name.name] += $name.number+"/"
}
foreach ($key in $hash.Keys) {
$values = $hash[$key] -replace ("/$")
$output += "$key - The number(s) associated with this person is/are: $values"
}
$output
Upvotes: 0
Reputation: 35338
A pipeline like this should do the job
Import-Csv .\test.csv |
Group-Object Name |
Foreach-Object {
$nums = $_.Group.Number;
"{0}- The number(s) associated with this person is/are: {1}" -f $_.Name, ($nums -join '/')
}
Upvotes: 3