1

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.

Simon
  • 238
  • 2
  • 3
  • 10
  • It is not clear whether your single column CSV files contain headers (if not, to add a header use: `$csv1 = Import-Csv "csv1.csv" -Header CSV1`). Than you might use this [`Join-Object`](https://www.powershellgallery.com/packages/Join) cmdlet: `$csv1 | FullJoin $csv2 | FullJoin $csv3`. See also: [In Powershell, what's the best way to join two tables into one?](https://stackoverflow.com/a/45483110/1701026) – iRon Dec 03 '19 at 16:12

1 Answers1

0

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

Community
  • 1
  • 1
Matthew
  • 1,412
  • 2
  • 20
  • 35
  • Thanks for the response. Looking at that code, does it assume that all three files are the same length? If so I should have said that the files are unlikely to be the same length. – Simon Dec 03 '19 at 16:12
  • So I have managed to get it working using your code, thanks very much. – Simon Dec 03 '19 at 16:24