根据一列

时间:2016-09-17 23:21:43

标签: powershell csv import scripting

我尝试使用PowerShell执行以下操作:

  1. 将CSV#1中一列的特定值与CSV#2进行比较。

  2. 如果它与该特定值匹配,则将新的CSV文件中包含或不包含标题的新行中的整个行(除了匹配的值以防止重复值)组合在一起

  3. 例如:匹配列' animal'

    CSV#1:

    animal, name, age
    dog, spot, 5
    cat, whiskers, 3
    iguana, lizzy, 1

    CSV#2:

    animal, color, eyes
    fish, yellow, 2
    dog, brown, 2

    结果:新文件CSV#3位于

    之下
    dog, spot, 5, brown, 2

    我尝试使用Import-Csv进行CSV#1,但我在使用if -match语句迭代CSV#2时出现问题...

1 个答案:

答案 0 :(得分:0)

只需迭代第一个CSV并检查第二个CSV是否包含相同的动物。如果是,请创建具有所需属性的新PsCustomObject,最后将对象转换为CSV:

$csv1 = 
@'
animal, name, age
dog, spot, 5
cat, whiskers, 3
iguana, lizzy, 1
'@ | ConvertFrom-Csv

$csv2 = 
@'
animal, color, eyes
fish, yellow, 2
dog, brown, 2
'@ | ConvertFrom-Csv

$csv1 | ForEach-Object  {
    $csv1Entity = $_
    $csv2Entity = $csv2 | where animal -eq $csv1Entity.animal
    if ($csv2Entity)
    {
        [PSCustomObject]@{
            animal = $csv1Entity.animal
            name = $csv1Entity.name
            age = $csv1Entity.age
            color = $csv2Entity.color
            eyes = $csv2Entity.eyes
        }
    }
} | ConvertTo-Csv -NoTypeInformation

<强>输出:

"animal","name","age","color","eyes"
"dog","spot","5","brown","2"