如果第一个 CSV 文件缺少行,则需要直接从第二个 CSV 文件中复制:
ipcsv 2.csv |? 'User Id' -notin (ipcsv 1.csv).'User Id' | epcsv 1.csv -Append
如果您还说用户 ID 在您的文件中是唯一的,您可以将唯一的行从两个 CSV 集中取出到第一个 CSV:
(ipcsv 1.csv, 2.csv) | sort -Unique 'User Id' | epcsv 1.csv -NoTypeInformation
或者,如果您说文件具有相同的用户 ID 但没有相同的其他列,并且第一个 CSV 中的条目存在但有一些空列,那么:
$csv1 = Import-Csv d:\file1.csv
$csv2 = Import-Csv d:\file2.csv
foreach ($csv1item in $csv1)
{
$csv2item = $csv2.Where{$_.'User Id' -eq $csv1item.'User Id'}
$item1Properties = $csv1item | Get-Member -MemberType NoteProperty | select -ExpandProperty Name
$item2Properties = $csv2item | Get-Member -MemberType NoteProperty | select -ExpandProperty Name
$sharedProperties = $item1Properties.where{$_ -in $item2Properties}
$sharedProperties | ForEach-Object {
$value = $csv1item."$_"
if ($value -eq '') {
$csv1item."$_" = $csv2item."$_"
}
}
}
$csv1 | Export-Csv D:\file1.csv -NoTypeInformation
另外,如果您说这两个文件具有在“用户 ID”处重叠的不同列,并且第一个 CSV 中完全缺少条目,而不是缺少列,那么这将从中添加它们第二个 CSV,只取它们之间重叠的属性(希望如此):
$csv1 = Import-Csv d:\file1.csv
$csv2 = Import-Csv d:\file2.csv
$item1Properties = ($csv1[0] | gm -M NoteProperty).Name
$newCsv1Items = foreach($csv2item in $csv2.Where{$csv1.'User Id' -notcontains $_.'User ID'}) {
$newcsv1Item = @{}
$item1Properties.ForEach{$newcsv1Item."$_" = $csv2item."$_"}
[PSCustomObject]$newcsv1Item
}
$newCsv1Items | Export-Csv -Append D:\file1.csv