0

I have couple of csv excel sheet, that looks like this

Editors note: if you have a csv, then post a text representation of that csv!

> Get-Content .\Sheet1.csv
Name,Age
Xavier,20
Liam,19
Lisy,21

> Get-Content .\Sheet2.csv
Name,Age
Liam,19
Lisy,21
Frank,25

Could someone help me to make it work and get a csv out.

I am trying to compare column 'Name' values from csv 1 to csv2:

  • if there is a match I want to store the value in an array called array 1, finally export it to csv. eg -Liam and Lisy
  • if they do not match I want to store the values on array 2, finally export it to csv. eg - Xavier

My code:

$source = Import-Csv C:\output\Source.csv 
$target = Import-Csv C:\output\Target.csv
Creating array to store vales
$match = New-Object System.Collections.ArrayList
$donotmatch = New-Object System.Collections.ArrayList
Comparing column values  
foreach ($i in $source) {
    foreach ($s in $i.name) {
        foreach ($t in $target) {
            if ($n -eq $t.name) {
                $match.Add($n)
            }
            else
            {
                $donotmatch.Add($n)
            }
        }
    }
}
$match.ToArray()
$donotmatch.ToArray()
2
  • 2
    You should take a look at Compare-Object. And of course even before that you should search for your question here in SO. Something like this is asked about at least 10 times a week. ;-) Commented Feb 21, 2019 at 13:26
  • 2
    Possible duplicate of Comparing csv files in Powershell using Compare-Object Commented Feb 21, 2019 at 14:22

1 Answer 1

0

This script:

$Sheet1 = Import-Csv .\Sheet1.csv
$Sheet2 = Import-Csv .\Sheet2.csv

Compare-Object $Sheet1 $Sheet2 -Property Name -PassThru |
    Select-Object * -ExcludeProperty SideIndicator | 
        Export-Csv Different.csv -NoTypeInformation

Compare-Object $Sheet1 $Sheet2  -Property Name -PassThru -IncludeEqual -ExcludeDifferent |
    Select-Object * -ExcludeProperty SideIndicator | 
        Export-Csv Equal.csv -NoTypeInformation

will yield these two files:

> Get-Content .\Equal.csv
"Name","Age"
"Liam","19"
"Lisy","21"

> Get-Content .\Different.csv
"Name","Age"
"Frank","25"
"Xavier","20"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I tried the script, It works fine when when the csv has only one column called Name. But when there are two columns and when Liam and Lisy have same age 21 on first csv and Frank and Xavier has same age 22 then it gives a very different result, can you help me here.
I can't follow, your script compares only the name property, as does mine. If want to also compare the Age, change to Compare-Object $Sheet1 $Sheet2 -Property Name,Age ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.