[quote quote=206478]Hello,

I have a .csv that looks like this;

Field1 **Key**Field2 Field3 Field4 Field5 Field6 Field7 Field8

Pr1 3378 John M 44 Y Green 1112223333

Pr2 4235 Steve T 21 N Red 2223331111

Pr4 3378 John M 44 Y Green 1112223333

Pr7 2346 Chris Y 32 Y Yellow 2221113333

I want the final result to look like this;

Field1 **Key**Field2 Field3 Field4 Field5 Field6 Field7 Field8

Pr1, Pr4 3378 John M 44 Y Green 1112223333

Pr2 4235 Steve T 21 N Red 2223331111

Pr7 2346 Chris Y 32 Y Yellow 2221113333

I’ve tried a few methods, but nothing that works.

Any idea how to accomplish this?

Thanks![/quote]

# https://powershell.org/forums/topic/concatenate-field-based-on-key-value/
# Script to 'combine' identical records
# Criteria: Identical value in $Keyfield
# Combining method: Add multiple values in $CombinedField
# Sam Boutros - 27 Feb 2020
#region Input
$InputFile = '.\test1.csv'
$KeyField = 'Field2'
$CombinedField = 'Field1'
#endregion
#region Prep - create input CSV sample
'"Field1","Field2","Field3","Field4","Field5","Field6","Field7","Field8"' | Out-File $InputFile
'"Pr1","3378","John","M","44","Y","Green","1112223333"' | Out-File $InputFile -Append
'"Pr2","4235","Steve","T","21","N","Red","2223331111"' | Out-File $InputFile -Append
'"Pr4","3378","John","M","44","Y","Green","1112223333"' | Out-File $InputFile -Append
'"Pr7","2346","Chris","Y","32","Y","Yellow","2221113333"' | Out-File $InputFile -Append
#endregion
#region Process
$myInput = Import-Csv $InputFile
$MyOutput = foreach ($Group in ($myInput | group $KeyField)) {
if ($Group.Count -eq 1) {
$Group.Group
} else {
$CombinedRecord = ($Group.Group[0]).psobject.copy()
$CombinedRecord.$CombinedField = foreach ($Record in $Group.Group) { $Record.$CombinedField }
$CombinedRecord
}
}
#endregion
#region Output
"Here's the sample CSV:"
$myInput | FT -a
"and here's the output:"
$MyOutput | FT -a
#endregion

Here's the sample CSV:
Field1 Field2 Field3 Field4 Field5 Field6 Field7 Field8
------ ------ ------ ------ ------ ------ ------ ------
Pr1 3378 John M 44 Y Green 1112223333
Pr2 4235 Steve T 21 N Red 2223331111
Pr4 3378 John M 44 Y Green 1112223333
Pr7 2346 Chris Y 32 Y Yellow 2221113333
and here's the output:
Field1 Field2 Field3 Field4 Field5 Field6 Field7 Field8
------ ------ ------ ------ ------ ------ ------ ------
{Pr1, Pr4} 3378 John M 44 Y Green 1112223333
Pr2 4235 Steve T 21 N Red 2223331111
Pr7 2346 Chris Y 32 Y Yellow 2221113333