title: batch file to copy newest backup file
body: <p>I've currently got a SQL job (SQL Server 2008 R2) that checks all the backup files in a folder and then dynamically creates a batch file to copy the most recent on to a new location with a new name so that it can be compressed will other backup files.</p>
  
  <p>I'm looking to turn this into a batch file on it's own without the need to run the SQL Server part first.  But can't work out how to find out the most recent backup file.  Some checking online has shown how to get the most recent file in a folder, but there are transaction log backups in the same folder.</p>
  
  <p>Basically I thought it would be something like:</p>
  
  <pre><code>for /f %%x in ('dir "J:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\CommonInterface\*.bak" /B /O:-D') do set NEWEST_BAK &amp; goto DONE
  
  :DONE
  copy "%newest%" F:\backup\new.bak
  Pause
  </code></pre>
  
  <p>but that gives the error:</p>
  
  <pre><code>Environment variable NEWEST_BAK not defined
  </code></pre>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>Thanks</p>
  
  <p>Alex</p>