Import Single Column CSV Files and join them into Single Three Column CSV File Powershell

醉酒当歌 提交于 2020-06-23 11:38:29

问题


I should start by saying I'm no PowerShell expert at all, I can cobble stuff together OK but that's about it.

I have 3 .csv files that all contain 1 column of information.

I need a PowerShell script that will combine each column from the individual CSV files and combine them into a single 3 column CSV file.

i.e.

CSV1
Red
Green
Blue

CSV2
Monday
Tuesday

CSV3
Monkey
Badger
Tiger
Giraffe

And that combined would look like

CSV1    CSV2    CSV3
Red     Monday  Monkey
Green   Tuesday Badger
Blue            Tiger
                Giraffe

So far I have looked creating an object and adding members, but it seems that each member can only have one value.

$csv1 = Import-Csv "csv1.csv"
$csv2 = Import-Csv "csv2.csv"
$csv3 = Import-Csv "csv3.csv"

$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name "Rule Block 1" -Value $csv1[2] $csv1[3]
$obj | Add-Member -MemberType NoteProperty -Name "Rule Block 2" -Value $csv2[2]
$obj | Add-Member -MemberType NoteProperty -Name "Rule Block 3" -Value $csv3[2]
$obj | Export-Csv "C:\Users\Simon\Desktop\FJ Stuff\Powershell\exportTest.csv" -NoTypeInformation

I'm not even sure if I'm heading in the write direction with this.

Any help here would be greatly appreciated.


回答1:


You could solve this by using:

$file1 = @(gc "x")
$file2 = @(gc "y")
$file3 = @(gc "z")

$combined = @()
for ($i=0; $i -lt $file1.Count; $i++) {
    $combined += $file1[$i] + ', ' + $file2[$i] + ', ' + $file3[$i]
    }

$combined | Out-File "C:\test.csv" -encoding default

Simply replace the x/y/z with the locations of the CSV, this should combine them into the test csv and look like:

title - title - title

x - y - z

x - y - z

x - y - z

x - y - z



来源:https://stackoverflow.com/questions/59160633/import-single-column-csv-files-and-join-them-into-single-three-column-csv-file-p

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!