Powershell CSV ForEach行在另一个csv中搜索单元格值并返回匹配项

时间:2019-10-02 15:59:52

标签: powershell csv

如果在其他地方回答了这个问题,我深表歉意。我一直在寻找解决方案好几天了。 我有2个CSV文件。 MasterFile.csv PhoneNumbers.csv 的格式如下。

MasterFile.csv

SomeData MoreData Phone      LastData

abcdefg hijklmnop 2222222222 qrstuvwx

PhoneNumbers.csv

Client_ID Phone1     Phone2     Phone3

12345     1111111111 2222222222 3333333333

对于 MasterFile.csv 中的每一行,我想在 PhoneNumbers.csv 的所有三列Phone1,Phone2和Phone3中搜索Phone。然后,如果Phone与任何列匹配,我想在新列中将Client_ID返回到 MasterFile.csv

预期结果

SomeData MoreData Phone      LastData Client_ID

abcdefg hijklmnop 2222222222 qrstuvwx 12345

1 个答案:

答案 0 :(得分:0)

一种方法是从PhoneNumbers.csv创建一个查找哈希表,其中的每个电话号码都是键,而Client_Id是值。

$master  = Import-Csv -Path 'D:\Test\MasterFile.csv'
$numbers = Import-Csv -Path 'D:\test\PhoneNumbers.csv'

# create a lookup Hashtable from the numbers
$lookup = @{}
$numbers | ForEach-Object {
    $lookup[$_.Phone1] = $_.Client_ID
    $lookup[$_.Phone2] = $_.Client_ID
    $lookup[$_.Phone3] = $_.Client_ID
}

# iterate through the master items and emit an object with the Client_ID attached
$result = $master | ForEach-Object {
    $id = if ($lookup.ContainsKey($_.Phone)) { $lookup[$_.Phone] } else { 'Unknown' }
    $_ | Select-Object *, @{Name = 'Client_ID'; Expression = {$id}}
}

#output on screen
$result | Format-Table -AutoSize

# output to (new) CSV file)
$result | Export-Csv -Path 'D:\Test\MasterFileComplete.csv' -NoTypeInformation

另一种方法,再次使用查找哈希表,是使用管道符号|组合三个电话号码,并将其用作键。 这将有效地成为可与正则表达式-match运算符一起使用的字符串,如下所示:

$master  = Import-Csv -Path 'D:\Test\MasterFile.csv'
$numbers = Import-Csv -Path 'D:\test\PhoneNumbers.csv'

# create a lookup Hashtable from the numbers
$lookup = @{}
$numbers | ForEach-Object {
    # combine the numbers with the pipe symbol which is OR in a regex match
    # your phone numbers may have formats with a country code like '+44 12345678'
    # so to be sure, you need to [regex]::Escape() each phone number
    $key = '{0}|{1}|{2}' -f [regex]::Escape($_.Phone1), 
                            [regex]::Escape($_.Phone2), 
                            [regex]::Escape($_.Phone3)
    $lookup[$key] = $_.Client_ID
}

# iterate through the master items and emit an object with the Client_ID attached
$result = $master | ForEach-Object {
    $phone = $_.Phone
    # find the matching phone number using regex
    $key = $lookup.Keys | Where-Object { $phone -match $_ }
    $id = if ($key) { $lookup[$key] } else { 'Unknown' }
    $_ | Select-Object *, @{Name = 'Client_ID'; Expression = {$id}}
}

#output on screen
$result | Format-Table -AutoSize

# output to (new) CSV file)
$result | Export-Csv -Path 'D:\Test\MasterFileComplete.csv' -NoTypeInformation

根据文件中的内容,屏幕上的输出将类似于

SomeData MoreData  Phone      LastData Client_ID
-------- --------  -----      -------- ---------
abcdefg  hijklmnop 2222222222 qrstuvwx 12345    
ijklmno  kjsdhsd   3333333334 qrstuvwx Unknown  
pqrstuv  qazwsx    5555555555 qrstuvwx 67890

P.S。为了安全起见,我正在写一个新的CSV文件,所以您不会覆盖原来的