title: Windows Batch File to Reduce PDF File Size
body: <p>I've been working on this Windows batch file to reduce the size of all of the PDF files in one directory ("C:\BigPDFs") and move them to a different directory ("C:\SmallPDFs") using Ghostscript. Ghostscript works great, but the problem I'm having is in the Windows batch file script:</p>
  
  <pre><code>for /R "%1" %%f in (*.pdf) do (
      SET outfile=%2\%%~nf%%~xf   
      gswin32c.exe -sDEVICE=pdfwrite -dMaxSubsetPct=100 -dPDFSETTINGS=/ebook -sOutputFile=%outfile% -dNOPAUSE -dBATCH "%%f"   
  )
  </code></pre>
  
  <p>The "C:\BigPDFs" directory has four files in it:</p>
  
  <ul>
  <li>TEST1.pdf (5 pages)</li>
  <li>TEST2.pdf (9 pages)</li>
  <li>TEST3.pdf (9 pages)</li>
  <li>TEST4.pdf (4 pages)</li>
  </ul>
  
  <p>I'm expecting it to write the same four compressed files to the "C:\SmallPDFs" directory, but the only one written is "TEST4.pdf". It appears that the %outfile% variable is always resolving to the last file name in the "C:\BigPDFs" directory ("TEST4.pdf"), even though it is processing all four files in sequence. The reason I know it's processing all four files is because the Ghostscript output displays "Processing pages 1 through 5", followed by "Processing pages 1 through 9", "Processing pages 1 through 9", and then finally "Processing pages 1 through 4".</p>
  
  <p>Why does the variable always resolve to the last file ("TEST4.pdf")? Is there a way to capture the "current" file name that it's processing and store it in a variable so that it retains the "current" file name when it runs Ghostscript?</p>