Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

powershell script for combining two csv files

$
0
0

I want to combine two csv files into one  like for example:

CS1 data:

id,name,des

23,wer,qw

14,er,32

2,,we

cs2 data:

number,next,issues

23,weq,23,

13,qwe,df

45,,ew

2,,tre

result csv should be like

id,name,des,next,issues

23,wer,qw,weq,23

14,er,32,,,

2,,we,,tre

,,,13,qwe,df

,,,45,,ew

for that i wrote a code

$csv1objs = get-content file1.txt

$csv2objs = get-content file2.txt

 

$combined_csv_objs = @()

$final = @()

 

$csv1objs | foreach-object {

    $csvtemp = @()

    $found = 0

$key1 = $_.id

$key1row = $_

$csv2ojbs | foreach-object {

$key2 = $_.number

$key2row = $_

if ($key1 -eq $key2) {

      $combined_csv_objs+=$key1row+','+$key2row

      $found = 1;

}

else 

        {

$csvtemp += $key2row

}

}

}

$key1row

    write-host "The combined contents are: "

    $combined_csv_objs

if ($found) {

 $csv2objs = $csvtemp}

 else { $combined_csv_objs += $combined_csv_objs+','+$key1row

       }

 

 

$csv2objs|foreach-object {

$key3row = $_

$final = $combined_csv_objs+','+$key1row

}

$final|set-content out.txt

but when I am not getting the expected result can anyone help with it

(I want the script to be in a generic way so that it will work any anyother csv files as well)

Thanks in advance!!!!


Viewing all articles
Browse latest Browse all 6937

Trending Articles