2017-04-20 73 views
-2

首次使用powershell。 我有2個csv文件。每個列具有不同的數量,並且具有不同的條目數量並且不以相同的順序。在共同列的基礎上比較兩個具有不同列編號的CSV文件

這裏是前幾行

的一些例子File1.csv

Name,Alias,Category 
    Comdty,CONTRACT FOR DIFFERENCE,Future 
    Comdty,Calendar Spread Option,Future 
    Corp,Bond,FixedIncome 
    Corp,EURO-DOLLAR,FixedIncome 
    Corp,FLOORSPREAD,FixedIncome 
    Corp,FRA,FixedIncome 

File2.CSV

Alias,Category 
EURO-DOLLAR,FixedIncome 
Bond,FixedIncome 
Preferred,Equity 

我需要比較使用基於Alias列的PowerShell腳本的文件,並將匹配值一起顯示,並顯示兩個文件中不存在值的空白處。 喜歡的東西:

Alias,Alias, Category ------------------------- MacthCase 
    ___,CONTRACT FOR DIFFERENCE,Future ------------ false 
    ___,Calendar Spread Option,Future ------------- false 
    Bond,Bond,FixedIncome ------------------------- true 
    EURO-DOLLAR,EURO-DOLLAR,FixedIncome ----------- true 
    ___,FLOORSPREAD,FixedIncome ------------------- false 
    ___,FRA,FixedIncome --------------------------- false 
    Preferred,___,Equity -------------------------- false 

回答

1

試試這個

#import files with select columns 
$file1=import-csv C:\temp\file1.csv | select Alias,Category, @{N="file";E={"file1"}} 
$file2=import-csv C:\temp\file2.csv | select Alias,Category, @{N="file";E={"file2"}} 

#merge into one list object 
$allfile=$file1 
$allfile+=$file2 

#group by Alias and build objects result 
$allfile | group Alias | foreach{ 

    if ($_.Count -ge 2) 
    { 
     [pscustomobject]@{Alias1=$_.Name;Alias2=$_.Name;Categorie=$_.Group.Category[0];MatchCase=$true} 
    } 
    else 
    { 
     if ($_.Group.file -eq "file1") 
     { 
      [pscustomobject]@{Alias1="____";Alias2=$_.Name;Categorie=$_.Group.Category;MatchCase=$false} 
     } 
     else 
     { 
      [pscustomobject]@{Alias1=$_.Name;Alias2="____";Categorie=$_.Group.Category;MatchCase=$false} 
     } 
    } 


} 
+0

類不能被加載「'不能索引到一個空array.'」真正的價值和它的到來空白全是假的值。它正在比較這些文件,但結果會以表格的形式連續出現。你能幫忙嗎? –

相關問題