[quick tip]
When I was working on my tiny series how to work with performance counters, I needed to merge two csv files together. It's very straightforward:


$f1 = Import-Csv -Delimiter $delimiter -Path $file1
$f2 = Import-Csv -Delimiter $delimiter -Path $file2

$count = [Math]::Min($f1.Count, $f2.Count)
if ($f1.Count -ne $f2.Count) {
    write-host "The sizes are not the same (f1: $($f1.Count) x f2: $($f2.Count))."
    write-host "Minumum will be used: $count"

$propsToAdd = $f2 | Get-Member -MemberType NoteProperty | Select-Object -expand Name
foreach($propName in $propsToAdd) { 
    Write-Debug "Property: $propName"
    foreach($i in 0..($count-1)) {
        Write-Debug " row: $i"
        try {
            Add-Member -InputObject $f1[$i] -MemberType NoteProperty `
                -Name $propName -Value $f2[$i]."$propName"
        catch [Exception] {
            Write-Host "Error when adding property" -ForegroundColor Red
            Write-Host " property: $propName" -ForegroundColor Red
            Write-Host " row: $i" -ForegroundColor Red
$f1[0..($count-1)] | Export-Csv -Delimiter $delimiter -Path $outputFile -NoTypeInformation
    In the first part (denoted as #1) we read the csv files into custom objects. The result is (for each csv files) an array of objects where each column is mapped to a property of the object. Values from objects in array in $f2 will be added to objects in array $f2.
    We read the property names of objects in $f2. Then we iterate through all the property names.
    We add 'properties' to the appropriate object taken from $f1. The objects from $f1 and $f2 are mapped to each other using the index $i.
    That's all. We export the result as csv file and we are done.

Meta: 2009-10-21, Pepa

Tags: csv PowerShell