如何将CSV文件与唯一的标题结合起来,并每行显示每个CSV的输出



我看到了许多关于如何组合CSV文件的例子,但没有一个完全符合我想要实现的目标。我有多个CSV文件,只包含一行,但包含多列。每个CSV中的每个标头可能不同,但它们之间确实有一个共同的列名。我想要完成的输出是将每个CSV文件的所有标头(无论显示的值是否为null(添加到输出CSV文件的第1行。然后,我想将每个CSV的单行输出与输出CSV文件中的一行对齐,并相应地填充每一列,并将那些没有分配值的列留空。

CSV1:

姓名、日期、年份、国家比尔,2018年5月1962年,加拿大

CSV2:

配置文件,Prov,大小,名称1,ON,14,Steve

CSV最终结果:

姓名、简介、尺寸、日期、年份、学历、国家Bill,,,2018年5月1962年,加拿大Steve,1,14,,,ON,,,

导入、提取、构造和导出。。。

$files = 'csv1.csv','csv2.csv'
$outputcsv = 'final.csv'
# import all files
$csv = $files | Import-Csv 
# extract columns from all files
$columns = $csv | ForEach {
$_ | Get-Member -MemberType NoteProperty | Select -ExpandProperty Name
}
# construct an object (from file 1) with all the columns
# this will build the initial csv
# (SilentlyContinue on members that already exist)
$columns | ForEach {
Add-Member -InputObject $csv[0] -Name $_ -MemberType NoteProperty -Value '' -ErrorAction SilentlyContinue
}
# export first object - and build all columns
$csv | Select -First 1 | Export-Csv -Path $outputcsv -NoTypeInformation
# export the rest
# -force is needed, because only 1st object has all the columns
$csv | Select -Skip 1 | Export-Csv -Path $outputcsv -NoTypeInformation -Force -Append
# show files
($files+$outputcsv) | ForEach { "$_`:"; (Get-Content -LiteralPath $_); '---' }

编辑:无需过度考虑导出。一行就足够了:.csv |导出csv-路径$outputsv-无类型信息

虽然还有另一个选项可以在带有Join-Object的一行中执行,您可以从PSGallery获取此cmdlet。

Find-Script join-object | Install-Script -Verbose -Scope CurrentUser

以下作品,

(Join-Object -Left $CSV1 -Right $CSv2 -LeftJoinProperty Name -RightJoinProperty Name ), (Join-Object -Left $CSV2 -Right $CSV1 -LeftJoinProperty Name -RightJoinProperty Name -Type AllInLeft) | Export-Csv -Path c:CombinedCsv.csv -NoTypeInformation

最新更新