2016-04-12 32 views
0

給定兩個CSV文件中扣除的比賽:比較兩個CSV文件,並從原來的

 
File1.csv 
SKU,Description,UPC 
101,Saw,101010103 
102,Drill,101010102 
103,Screw,101010101 
104,Nail,101010104 

File2.csv 
SKU,Description,UPC 
100,Light,101010105 
101,Saw,101010103 
104,Nail,101010104 
106,Battery,101010106 
108,Bucket,101010114 

我想創建一個新的CSV文件,我們會打電話給UpdatedList.csv,有從File1中的每個條目。 csv減去SKU在File1.csv和File2.csv中的任何行。在這種情況下,UpdatedList.csv看起來像

 
UpdatedList.csv 
"SKU","Description","UPC" 
"102","Drill","101010102" 
"103","Screw","101010101" 

以下代碼將做我想要的,但我相信有一個更有效的方法。我怎樣才能做到這一點沒有循環?我的代碼如下。

#### Create a third file that has all elements of file 1 minus those in file 2 ### 
$FileName1 = Get-FileName "C:\LowInventory" 
$FileName2 = Get-FileName "C:\LowInventory" 
$f1 = ipcsv $FileName1 
$f2 = ipcsv $FileName2 
$f3 = ipcsv $FileName1 
For($i=0; $i -lt $f1.length; $i++){ 
For($j=0; $j -lt $f2.length; $j++){ 
if ($f1[$i].SKU -eq $f2[$j].SKU){$f3[$i].SKU = 0} 
} 
} 
$f3 | Where-Object {$_.SKU -ne "0"} | epcsv "C:\LowInventory\UpdatedList.csv" -NoTypeInformation 
Invoke-Item "C:\LowInventory\UpdatedList.csv" 
################################ 

回答

1

您可以通過採取集團對象cmdlet的優勢,做到不循環:

$f1 = ipcsv File1.csv; 
$f2 = ipcsv File2.csv; 
$f1.ForEach({Add-Member -InputObject $_ 'X' 0}) # So we can select these after 
$f1 + $f2     | # merge our lists 
    group SKU    | # group by SKU 
    where {$_.Count -eq 1} | # select ones with unique SKU 
    select -expand Group | # ungroup 
    where {$_.X -eq 0}  # where from file1 
相關問題