title: Powershell Writing to .XLSX is Corrupting the Files
body: <p>I have a Powershell script that loops through .xslx files in a folder and password protects them with the file name (for now.) I have no problem looping through and writing to .xls, but when I try to open an .xlsx file after writing it with Powershell - I get the error:</p>
  
  <blockquote>
    <p>Excel cannot open the file 'abcd.xlsx' because the file format or file
    extension is not valid. Verify that the file has not been corrupted
    and that the file extension matches the format of the file.</p>
  </blockquote>
  
  <p>Here's the script:</p>
  
  <pre><code>function Release-Ref ($ref) { 
      ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( 
      [System.__ComObject]$ref) -gt 0) 
      [System.GC]::Collect() 
      [System.GC]::WaitForPendingFinalizers()  
      } 
  
  $e = $ErrorActionPreference
  $ErrorActionPreference="continue"
  foreach ($f in Get-ChildItem "C:"){
      try{
          $ff = $f
          $xlNormal = -4143 
          $s = [System.IO.Path]::GetFileNameWithoutExtension($f)
          $xl = new-object -comobject excel.application 
          $xl.Visible = $False
          $xl.DisplayAlerts = $False   
          $wb = $xl.Workbooks.Open($ff.FullName)
          $wb.sheets(1).columns("A:S").entirecolumn.AutoFit()
          $wb.sheets(1).columns("N").NumberFormat = "0.0%"
          $a = $wb.SaveAs("C:\Out\" + $s + ".xls",$xlNormal,$s) #works
          #$a = $wb.SaveAs("C:\Out\" + $s + ".xlsx",$xlNormal,$s) #doesn't work
          $a = $xl.Quit() 
  
          $a = Release-Ref($ws) 
          $a = Release-Ref($wb) 
          $a = Release-Ref($xl) 
      }
      catch {
          Write-Output "Exception"
          $ErrorActionPreference=$e;
      }
  }
  </code></pre>
  
  <p>I've searched other questions but can't find any other examples of the same issues writing from Powershell. Thank you.</p>