When encountered the next record, read all the lines from the prior record using powershell script

I've edited the post with more details description. My Input.DAT has 3 records, each record starts with "01".

   01 firstN1 lastN1 234      dfgh
   02 studentid1 sdf course1 345  
   03 class1 dfg 456                35        dfg
   05 dfgdf dghfg    sdfh                123       45
   01 firstN2 lastN2 567  
   02 studentid2 ert 568  
   03 class2 dfg location2 890
   01 firstN3 lastN3 567  
   03 class3 dfg location3 890

My Powershellscript.ps1 file:

    foreach-object {  
       $line = $_.tostring()  
      $i= $line.substring(0, 2).trim()    
        if($i -eq "01"){  
        if($i -eq "02"){  
    $=$line.substring(18,7).trim() }  
        if($i -eq "03"){  

# need help in below logic   

     Foreach ($x in $1) {   
         if ($x -eq '01') {   
    add-content -path outputfile.txt -value   firstname,"|",$lastname,"|",$studentid,"|",$class,"|",$course,"|",$location
Clear-Variable -Scope Script firstname*, lastname*, studentid*, class*, course* ,location*

My issue is : Current code is looking for the 1st "01" and reading only data(01 firstN1 lastN1 234)to the output file. however i want the logic to be written to check when the loop hits 2nd "01" or/and the $firstname again ,that when we know we have completed reading first set of records , then only read all the previous record to the output file in single line.

My Output file(outputfile.txt) looks like this.

Instead of 

Thanks in advance.