title: How to get latest modified file in nested, multiple directories?
body: <p>This is my folder structure</p>
  
  <pre><code>Temp
  - Folder ZZZ (Created on 7 Feb)
  -- FileA.bak (Created on 7 February)
  -- FileB.bak (Created on 8 February)
  -- FileC.bak (Created on 9 February)
  - Folder B   (Created on 10 Feb)
  -- FileD.bak (Created on 10 February)
  -- FileE.bak (Created on 11 February)
  -- FileF.bak (Created on 12 February)
  </code></pre>
  
  <p>Currently, I'm using the code below to get the latest .bak file recursively.</p>
  
  <p><code>FOR /F "delims=|" %%I IN ('DIR /s "D:\Temp\*.bak" /b /O:D') DO SET latestBakFile=%%I</code> </p>
  
  <h2>Problem</h2>
  
  <p>The code above works well when there is only a single subdirectory. In cases when there is multiple sub-directories, it starts to break. E.g., in the folder structure above, getting the latest file always results in <code>FileC.bak</code>. The result I expected was <code>FileF.bak</code> </p>
  
  <p><strong>Reasoning to problem</strong></p>
  
  <p>I did a test with <code>DIR /s "D:\Temp\*.bak" /b /O:D</code>, interchanged <code>/O:D</code> with <code>/O:-D</code> and found that the sub-directories are always sorted in alphabetical order first before sorting the files according to date modified time in the directories. I figured this was the cause. </p>
  
  <p>Is there a way in which I can always get the latest <code>.bak</code> file in the <code>Temp</code> directory irregardless of which sub-directory the <code>.bak</code> file is located in?</p>