title: PowerShell: Export Excel sheets as CSV
body: <p>I figured out how to export all sheets of a workbook as csv using powershell for excel 2007. The problem I have is that the script exports the same sheet 2x randomly. Sometimes it creates the 3 separate csv files like it should, and sometimes one of the csv files is a copy of another.
  But it always prints:</p>
  
  <pre><code>A
  B
  C
  </code></pre>
  
  <p>Here is the code:</p>
  
  <pre><code>$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
  Add-Type -AssemblyName Microsoft.Office.Interop.Excel
  
  $excel = new-object -ComObject "Excel.Application";
  $excel.DisplayAlerts=$True;
  $excel.Visible =$false;
  $wb = $excel.Workbooks.Open($scriptPath + "\file.xlsx");
  foreach($ws in $wb.Worksheets) {
      if($ws.name -eq "A" -or $ws.name -eq "B" -or $ws.name -eq "C") {
          Write-Host $ws.name;
          $ws.SaveAs($scriptPath + "\" + $ws.name + ".csv", [Object] Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVMSDOS);
  }
  }
  $wb.close($False)
  $excel.Quit();
  [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel);
  </code></pre>
  
  <p>Running on Windows 7 x64, Excel 2007 SP2</p>