i have 2 txt file in powershell each having four Lines i need to join two texts into one text file

160 views Asked by At
First.txt
10.10.10.10
10.9.9.9
10.8.8.8
10.7.7.7

Second.txt
xx-xx-xx-xx-xx-xx
yy-yy-yy-yy-yy-yy
zz-zz-zz-zz-zz-zz
aa-aa-aa-aa-aa-aa

first text file is the ip address and second text file is the mac details for the ip address, i need output like below,this ip address are in foreach loop so each ipaddress will be checked for mac details and stores out put in second.txt

10.10.10.10 mac details are xx-xx-xx-xx-xx-xx
10.9.9.9 mac details are yy-yy-yy-yy-yy-yy

i have tried all ways but getting output like

10.10.10.10
10.9.9.9
10.8.8.8
10.7.7.7
mac details are 
xx-xx-xx-xx-xx-xx
yy-yy-yy-yy-yy-yy
zz-zz-zz-zz-zz-zz
aa-aa-aa-aa-aa-aa

code i used is

get-content first.txt,second.txt | set-content joined.txt
1

There are 1 answers

0
FoxDeploy On

This isn't very hard to do, joining these two files.

The key is to load both files as variables then use a for loop to step through both files, one at a time, and assemble the new output.

$first = get-content C:\temp\stack\first.txt
$second = get-content C:\temp\stack\second.txt
$newfile = New-Object System.Collections.ArrayList

for ($i = 0; $i -lt $first.Count ; $i++)
{     
    "getting content from row number $i from both first and second to make a new row..."
    
    $newRow = "$($first[$i]) mac details are $($second[$i])"
    
    #add new row and copy the row number
    $rowNumber = $newfile.Add($newRow)

    "`t`tnew row added as row # $rowNumber in output variable"
}

$newfile | Out-File C:\temp\stack\out.txt 

This syntax "$($first[$i]) mac details... says make a new string, and then get the value of whats in the $first, in the row or position number $i.

The output will look like this:

getting content from row number 0 from both first and second to make a new row...
        new row added as row # 0 in output variable
getting content from row number 1 from both first and second to make a new row...
        new row added as row # 1 in output variable

I made it extra verbose to teach the principles behind what I'm doing, for you and future readers. Learning these techiques of stepping through files one at a time, cleaning up or building new output files put you on a path to success in PowerShell :)