title: Parsing a comma separated file using powershell
body: <p>I have a text file which contains several lines, each of which is a comma separated string.  The format of each line is:</p>
  
  <p><code>&lt;Name, Value, Bitness, OSType&gt;</code> </p>
  
  <p><code>Bitness</code> and <code>OSType</code> are optional.</p>
  
  <p>For example the file can be like this:</p>
  
  <pre><code>Name1, Value1, X64, Windows7
  Name2, Value2, X86, XP
  Name3, Value3, X64, XP
  Name4, Value3, , Windows7
  Name4, Value3, X64 /*Note that no comma follows X64 */
  ....
  ....
  </code></pre>
  
  <p>I want to parse each line into 4 variables and perform some operation on it.  This is the PowerShell script that I use..</p>
  
  <pre><code>Get-Content $inputFile | ForEach-Object {
      $Line = $_;
  
      $_var = "";
      $_val = "";
      $_bitness = "";
      $_ostype = "";
  
      $envVarArr = $Line.Split(",");
      For($i=0; $i -lt $envVarArr.Length; $i++) {
          Switch ($i) {
              0 {$_var = $envVarArr[$i].Trim();}
              1 {$_val = $envVarArr[$i].Trim();}
              2 {$_bitness = $envVarArr[$i].Trim();}
              3 {$_ostype = $envVarArr[$i].Trim();}
          }                                    
      }
      //perform some operation using the 4 temporary variables
  }
  </code></pre>
  
  <p>However, I wanted to know if it is possible to do this using regex in PowerShell.  Would you please provide sample code for doing that?  Note that the 3rd and 4th values in each line can be optionally empty.</p>