给出两个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"
################################
答案 0 :(得分:1)
通过利用Group-Object 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