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"){  
    $firstname=$line.substring(3,7).trim()  
    $lastname=$line.substring(11,6).trim()}  
   
      
        if($i -eq "02"){  
    $studentid=$line.substring(3,10).trim()
    $=$line.substring(18,7).trim() }  
      
    
        if($i -eq "03"){  
    $class=$line.substring(3,6).trim()
    $location=$line.substring(14,9).trim()} 
      

# 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.
       firstname|lastname|studentid|class|course|location
       firstN1|lastN1||||
       firstN2|lastN2|studentid1|class1|course1||
       firstN3|lastN3|studentid2|class2||location2

Instead of 
       firstname|lastname|studentid|class|course|location
       firstN1|lastN1|studentid1|class1|course1||  
       firstN2|lastN2|studentid2|class2||location2
       firstN3|lastN3|studentid3|class3||location3

Thanks in advance.