简体   繁体   English

用powershell比较两个csvs并将值从一个转换为另一个

[英]Compare two csvs with powershell and take value from one into other

I have two CSVs in powershell that I am trying to extract data from and put into a csv.我在 powershell 中有两个 CSV,我试图从中提取数据并将其放入 csv。 For example: contacts.csv with First, Last, Email mailinglist.csv with First,Last,Email例如:contacts.csv with First, Last, Email mailinglist.csv with First,Last,Email

MailingList email is blank, and I need to pull the email addresses from contacts.csv MailingList 电子邮件是空白的,我需要从contacts.csv 中提取电子邮件地址

Mailinglist has some, but not all, of the contacts as contacts.csv.邮件列表包含一些(但不是全部)联系人,如contacts.csv。 I need to pull the email addresses from contacts.csv only for the rows that have a match in Mailinglist.csv我只需要为 Mailinglist.csv 中匹配的行从contacts.csv 中提取电子邮件地址

So far I have:到目前为止,我有:


    $contacts = Import-Csv .\contacts.csv
    $mailing = Import-Csv .\mailing.csv

    $compare = $mailing | select $_ | $_ -notcontains $contacts
    $email = $contacts | Select $_ | Where { $_ -contains $compare }

$compare gives me the correct First and Last columns. $compare 给了我正确的 First 和 Last 列。 Correct being that it only returns values matching $mailing, not anything else.正确的是它只返回匹配 $mailing 的值,而不返回任何其他值。

The $email variable comes back empty. $email 变量返回空。

Help?帮助? I have a spreadsheet with 850 records I would really like to not have to do manually...我有一个包含 850 条记录的电子表格,我真的不想手动做...

What you're looking for is called a 'left join'.您要查找的内容称为“左连接”。 Try searching around for a join (possibly this good explanation from Join-Object will help you figure out what you need) in Powershell and you should find some applicable examples.尝试在 Powershell 中搜索连接(可能来自Join-Object 的这个很好的解释将帮助您弄清楚您需要什么),您应该找到一些适用的示例。 There are a few types of joins, like ' inner join ' and 'left/right join' as well.有几种类型的连接,例如“ 内连接”和“左/右连接”。

Powershell doesn't have great built-in functions for joining, so you'll likely need a small function or two. Powershell 没有用于加入的强大内置函数,因此您可能需要一两个小函数。

Just by looking at your code though, you may want to try changing: Where { $_ -contains $compare }只是通过查看您的代码,您可能想尝试更改: Where { $_ -contains $compare }

To: Where { $compare -contains $_ }到: Where { $compare -contains $_ }

The following is the solution using Compare-Object .以下是使用Compare-Object的解决方案。

Compare-Object $contacts $mailing -Property First,Last -IncludeEqual -ExcludeDifferent -PassThru |
select * -ExcludeProperty SideIndicator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM