Search code examples
powershellpowershell-cmdlet

Get content from 2 files and insert into 1 file


Hello guys,

I'm trying to insert content from the 2 files into 2 columns new final.txt

Their are only one column in each file

example:

import file1.txt

import file2.txt

export final.txt

$file1 = Get-Content .\test1.txt
$file2 = Get-Content .\test2.txt
foreach ($i in $file1){
   foreach($y in $file2){
      Write-Host "$i" +  Write-Host "$y"
   }
}
Out-File .\final.txt

Solution

  • You can use th following using arrays :

    $file1 = Get-Content .\test1.txt
    $file2 = Get-Content .\test2.txt
    0..$($file1.Length-1) | % {add-Content -Value "$($file1[$_]), $($file2[$_])" -Path final.txt} 
    

    In the expression a..b, .. is the range operator that gives a collection of integer from a to b see about_operators.