Home > Mobile >  Powershell Compare 2 csv files on 2 objects and upload a 3 file
Powershell Compare 2 csv files on 2 objects and upload a 3 file

Time:09-17

I want to compare 2 csv files test1 and test2. I want to export a test3 file only if the Department or the country has changed with the changed details. I have the following code but this compares the 2 whole files not just the Country and Department:

Compare-Object -ReferenceObject (Get-Content -Path C:\scripts\test1.csv) -DifferenceObject (Get-Content -Path C:\scripts\test2.csv) -PassThru | Where-Object{ $_.SideIndicator -eq "=>" } |  % { $_ -Replace ',', ";"} | Out-File -FilePath C:\scripts\test3.csv

This is test1: enter image description here

This is test2: enter image description here

So test3 should be the same as test2. Anyone knows how you can compare the 2 files with just the changes of the country or department

CodePudding user response:

Without using Compare-Object, you can do this like below:

$csv1 = Import-Csv -Path 'C:\scripts\test1.csv'
$csv2 = Import-Csv -Path 'C:\scripts\test2.csv'

$csv3 = foreach ($item in $csv2) {
    $compare = $csv1 | Where-Object { $_.email -eq $item.email }
    if ($compare.Country -ne $item.Country -or $compare.Department -ne $item.Department) {
        # output the object from $csv2 to be collected in the new $csv3
        $item
    }
}

$csv3 | Export-Csv -Path 'C:\scripts\test3.csv' -Delimiter ';' -NoTypeInformation

If you do want to use Compare-Object, this also works:

$csv1 = Import-Csv -Path 'C:\scripts\test1.csv'
$csv2 = Import-Csv -Path 'C:\scripts\test2.csv'

Compare-Object -ReferenceObject $csv1 -DifferenceObject $csv2 -Property Country,Department -PassThru |
Where-Object{ $_.SideIndicator -eq "=>" } | Select-Object * -ExcludeProperty SideIndicator |
Export-Csv -Path 'C:\scripts\test3.csv' -Delimiter ';' -NoTypeInformation
  • Related