title: Windows 'dir' command: sort files by date when '/s' is specified
body: <p><strong>Goal:</strong> I want to copy the latest file with a certain extension from a "source directory" to a "destination directory" using a batch file. The latest file may be under several sub-directories within the source directory.</p>
  
  <p><a href="https://stackoverflow.com/q/97371/7355697">This question/answer</a> is exactly what I want, however it does not seem to sort when the <code>/s</code> option is specified (as <a href="https://stackoverflow.com/questions/97371/how-do-i-write-a-windows-batch-script-to-copy-the-newest-file-from-a-directory#comment8209811_978259">this comment would suggest</a>):</p>
  
  <pre><code>FOR /F "delims=|" %%I IN ('DIR "K:\path\tp\source\dir\*.ext" /B /S /O:D') DO SET NewestFile=%%I
  copy "%NewestFile%" "C:\path\to\destination\dir"
  </code></pre>
  
  <p>You can test <code>DIR "K:\path\tp\source\dir\*.ext" /B /S /O:D</code> by itself to see that it does not sort.</p>
  
  <p><strong>What I've Tried:</strong> This command by itself does work: <code>DIR "K:\path\tp\source\dir\*.ext" /S /B | sort</code> but I can't figure out how to use it in a for loop (batch file exits before I can determine the error - even with a <code>pause</code> at the end).</p>
  
  <p>Any ideas?</p>
  
  <p>See: <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/dir" rel="nofollow noreferrer">dir docs</a></p>