Search code examples
powershellcsvopencsvexport-csv

How to compare 2 CSV files in powershell


I'm trying to compare 2 CSV files with logs info in (logs_all, logs_new) format:

enter image description here

I want to add the rows they don't exist in logs_all from logs_new

$csv1 = Import-Csv $csvLogs_all -Delimiter "`t"
$csv2 = Import-Csv $csvLogs_new -Delimiter "`t"

$end     = $csv1.Count
$count   = 0
$diffobj = @()

# testtable is the name of the column, adjust it to your column header name
if($csv1.time[$count] -ne $csv2.time){
   $diffobj += $csv2[$count]
}

$count++
}until($count -eq $end)
Write-Host "chekking logs"
$diffobj | export-csv $csvLogs_all -NoTypeInformation

but this isn't working well, can some help me?


Solution

  • Have a look at the Compare-Object cmdlet.

    The cmdlet does the following:

    The Compare-Object cmdlet compares two sets of objects. One set of objects is the "reference set," and the other set is the "difference set."

    The result of the comparison indicates whether a property value appeared only in the object from the reference set (indicated by the <= symbol), only in the object from the difference set (indicated by the => symbol) or, if the IncludeEqual parameter is specified, in both objects (indicated by the == symbol).

    In other words, it compares two objects and tells you the differences.

    To compare two CSV files you can run

    $file1 = import-csv -Path "C:\temp\Test1.csv" 
    $file2 = import-csv -Path "C:\temp\Test2.csv" 
    Compare-Object $file1 $file2 -property ColumnName -IncludeEqual