Powershell比较2个csv文件并从第一个文件中删除重复文件,每个文件都有不同的头

Powershell比较2个csv文件并从第一个文件中删除重复文件,每个文件都有不同的头,powershell,csv,Powershell,Csv,我有2个Csv文件,第一个包含标题 姓名、电子邮件、电话 账单,Bill@jump.com,123-456-7890 第二个仅包含: primaryEmail Bill@jump.com 我想比较2,并删除任何重复的行在第一个,如果该电子邮件存在于第二个。我正在尝试使用比较对象,但不确定从这里到哪里 $File1 = Import-Csv C:\it\newuser.csv $File2 = Import-Csv C:\it\email.csv Compare-Object $File1

我有2个Csv文件,第一个包含标题

姓名、电子邮件、电话
账单,Bill@jump.com,123-456-7890
第二个仅包含:

primaryEmail
Bill@jump.com
我想比较2,并删除任何重复的行在第一个,如果该电子邮件存在于第二个。我正在尝试使用比较对象,但不确定从这里到哪里

$File1 = Import-Csv C:\it\newuser.csv
$File2 = Import-Csv C:\it\email.csv


Compare-Object $File1 $File2 -Property email

最简单的方法可能只是首先从第二个CSV获取主电子邮件,然后使用从第一个CSV过滤出重复电子邮件的重复行

# Get primary emails from 2nd CSV
$csv2 = (Import-Csv -Path .\2.csv).primaryEmail

# Remove rows from 1st csv that don't have an email in $csv2
$removedDuplicateRows = Import-Csv -Path .\1.csv | Where-Object {$_.Email -notin $csv2}

# Export filtered rows into output.csv
$removedDuplicateRows | Export-Csv -Path .\output.csv -NoTypeInformation
如果您使用的是PowerShell 7,则可以使用中的
-UseQuotes Never
在输出CSV中不包含引号

提供了一个有效的解决方案

但是,对于大型输入集,性能可能会成为一个问题,因为对每个CSV输入行执行电子邮件地址数组(
$csv2
)的线性搜索

使用提供了一种解决方案,因为哈希集中的查找速度始终很快

该方法提供了一种方便的方法,可以从实现的对象(如数组)构造这样的哈希集

# Build a case-insensitive hash set of email addresses from $File2 
# whose elements are to be excluded from $File1.
# Note that the cast to [string[]] is required in order for PowerShell
# to find the right generic method overload.
$refEmailsHashSet = [Linq.Enumerable]::ToHashSet(
  [string[]] (Import-Csv $File2).primaryEmail,
  [StringComparer]::CurrentCultureIgnoreCase
)

# Import $File1 and filter out the email addresses from $File2
# Pipe to `Export-Csv -NoTypeInformation -Encoding ...` to save to a new CSV file.
Import-Csv $File1 | Where-Object { -not $refEmailsHashSet.Contains($_.Email) }

是的,如果第二个csv有该电子邮件,我只想删除第一个csv中的行。这就是我要找的,谢谢你的帮助。