So I have two csv files (list1.csv and list2.csv) They both have these columns:

FirstName  LastName  MiddleName  City

I want to check list1.csv and see if any rows match a row from list2.csv and if so to remove it from list1.

$list1 = import-csv list1.csv
$list2 = import-csv list2.csv

foreach ($item in $list2)
$list1 = $list1 | Where {$_.FirstName -ne $item.FirstName -and $_.LastName -ne $item.LastName -and $_.MiddleName -ne $item.MiddleName -and $_.City -ne $item.City} 

This gives me a list that contains close to what I want but the and statements in the where clause seem to apply to the whole of list1 and not each line so it drops some entries I would expect to be present. There is probably a better way to do this but I am not coming up with much.

1 Answer 1


$list1 | Where-Object ... will run through every element of $list1, so there's no need to use foreach. Also, you can compare your CSVs via the Compare-Object cmdlet:

$list1 = @(Import-Csv .\list1.csv)
$list2 = @(Import-Csv .\list2.csv)

$list1 = @($list1 | Where-Object {
    @(Compare-Object $_ $list2 -Property FirstName,LastName,MiddleName,City -IncludeEqual -ExcludeDifferent).count -eq 0
  • That did it. Compare-object, I've made sure to explore that some more. Thanks again. Commented Nov 29, 2017 at 12:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .