Actually after further testing I found some logic errors that caused additional lines to be added to both the description of similar line and individually. Here is the updated code. I typically discourage using Foreach-Object when using a foreach statement could help avoid having to stash current objects to variables. However, the need to export to CSV and using -begin/-end blocks I feel warrant making an exception to this rule of thumb. (Specifically referring to $currobj = $_ )
Here was the extended sample data I tested with.
$csv = @'
Category,Description,Number,Fresh
Fruit,Grape,3,Yes
Vegetable,Lettuce,3,Yes
Fruit,Grape,3,Yes
Fruit,Apple,3,Yes
Vegetable,Tomato,3,No
Vegetable,Onion,3,No
Fruit,Grape,3,No
Fruit,Banana,3,No
Fruit,Banana,3,Yes
'@ | ConvertFrom-Csv
Updated script
$csv | foreach -Begin{
$result = @()
function Add-Line($newline){
[PSCustomObject]@{
'Category' = $newline.category
'Description' = $newline.description
'Number' = $newline.number
'Fresh' = $newline.fresh
}
}
} -process {
$currobj = $_
if($lines = $result | where category -eq $currobj.category)
{
if($matchinglines = $lines | where {$_.number -eq $currobj.number -and $_.fresh -eq $currobj.fresh})
{
if($matchinglines.description -notmatch $_.description)
{
$matchinglines.description = $matchinglines.description,$_.description -join ','
}
}
else
{
$result += Add-Line $_
}
}
else
{
$result += Add-Line $_
}
} -End {$result} | ConvertTo-Csv -NoTypeInformation
Output
"Category","Description","Number","Fresh"
"Fruit","Grape,Apple,Banana","3","Yes"
"Vegetable","Lettuce","3","Yes"
"Vegetable","Tomato,Onion","3","No"
"Fruit","Grape,Banana","3","No"
Just change ConvertTo-Csv to Export-Csv