在两个单独的csv中匹配两列,然后合并一列

时间:2016-09-27 20:37:08

标签: powershell

我有2张CSV。

SOURCE CSV

"Employee ID","username","givenname","surname","emailaddress","title","Division","Location"
"204264","ABDUL.JALIL@domain.com","Abdul Jalil","Bin Hajar","Abdul.jalil@domain.com","Warehouse Associate I","Singapore","Singapore, "
"30053","ABEL.BARRAGAN@domain.com","Abel","Barragan","Abel.Barragan@domain.com","Manager, Customer Programs - CMS","Germany","Norderstedt, "

更改CSV

givenname,surname,samaccountname,emailaddress,mail,country,city,state
Abigai,Teoyotl Rugerio,Abigai.Teoyotl,Abigai.TeoyotlRugerio@domain.com,Abigai.TeoyotlRugerio@domain.com,MX,,
Adekunle,Adesiyan,Adekunle.Adesiyan,Adekunle.Adesiyan@domain.com,Adekunle.Adesiyan@domain.com,US,VALENCIA,CALIFORNIA

我想将姓氏和名字从SOURCE与CHANGE匹配,如果匹配,请从CHANGE CSV中抓取“emailaddress”并将其放入SOURCE CSV中的新列。

到目前为止,我一直坚持匹配名字和姓氏列。

$source = import-csv .\ur.csv
$change = import-csv .\all.csv

$Matchgivenname = Compare-Object $source.givenname $change.givenname -IncludeEqual -ExcludeDifferent -PassThru
$matchsurname = Compare-Object $source.surname $change.surname -IncludeEqual -ExcludeDifferent -PassThru

2 个答案:

答案 0 :(得分:0)

不确定您是否可以同时使用Compare-Object,但您可以遍历所有原始员工,并为每个员工搜索任何更改。 e.g。

faxView.src = 'a particular directory

(未测试的)

答案 1 :(得分:0)

如果change CSV很大并且您只需要更改的电子邮件地址,请使用givenname + surname作为键构建哈希表,并将电子邮件作为值。然后在导入源CSV时使用它。

哈希表查找比枚举所有已更改数据行要快得多,因此迭代的总数将在#changed + #source + log2(#changed)左右,其中#代表行数。

此外,由于通过Add-Member添加新列比直接分配慢,因此只需使用自第一行提取的源字段和更改的电子邮件组成的自定义标头添加此新列一次。

$changedEmail = @{}
Import-Csv .\all.csv |
    ForEach { $changedEmail[$_.givenname + '|' + $_.surname] = $_.emailaddress }

$newHeader = ((Import-Csv .\ur.csv | Select -first 1).PSObject.Properties |
    Select -expand name) + 'changedemailaddress'
$combined = Import-Csv .\ur.csv -Header $newHeader | Select -skip 1 |
    ForEach {
        $_.changedemailaddress = $changedEmail[$_.givenname + '|' + $_.surname]
        $_
    }
$combined