How can I use Powershell to compare two CSV files, then update the one of the CSV files with results of comparison
17:06 07 Jan 2020

I would like to compare two CSV files; a 'master' and an 'input' file. I would like to update the 'master' file wherever a difference exists between it and the input file.

The 'master' file will initially contain some data like this:

A,B,C
5,9,cat
1,2,dog
2,8,rabbit
8,8,mouse
6,2,duck

The 'input' file may have entries which differ from the master file or which the master file does not have at all. In either of those cases, the master file should be updated to reflect the changes in the input file.

Input file example data:

A,B,C
1,2,otter
8,8,mouse
5,3,tiger

Using the examples above, where the input file's rows are compared to the master file, there is a difference between master and input for the line starting 1,2:

  • the master file contains: 1,2,dog
  • the input file contains: 1,2,otter

An update to the master file will be required such that it says 1,2,otter.

The input file also contains a new entry, 5,3,tiger, so the master file will be appended with that new data. After every row is checked, the master file should now look like this:

A,B,C
5,9,cat
1,2,otter
2,8,rabbit
8,8,mouse
6,2,duck
5,3,tiger

Here is the code that I have:

$apples = Get-Content $Input
$oranges = Get-Content $Master

# this will generate the file that contains ONLY the CHANGED or new entries that must be recorded
Compare-Object $apples $oranges -PassThru | Where-Object{ $_.SideIndicator -eq "<=" } | Out-File $OutFile

# this will generate the file that contains the old entries that need to be replaced with the new ones
Compare-Object $apples $oranges -PassThru | Where-Object{ $_.SideIndicator -eq "=>" } | Out-File $FixUp

Here is where I am stuck... I can get the 'input' changes and the 'old' entries, but I don't know how to use them to update the master file.

I was thinking of looping through the files. How do I correlate the master to the input file changes?

$csv = Import-Csv $FixUp

for($i = 0; $i -lt @($csv).Length; $i++){
   
    #$find = how do i get old csv value from master file ???
    #$replace = $csv
    #(Get-Content $file).replace($find, $replace) | Set-Content $file            
}
powershell csv