I just had a need to process a sorted folder the other day and these answers helped me get what I needed. My issue was that I needed to sort folder name and they were in the format XXX99.9.99.99. Windows, naturally, sorted them correctly. However, DIR did not since some of the numbers were single digits and some were double/triple digits. In my batch file, I combined the DOS FOR command with a call out to powershell using the answer provided here:
How to sort by file name the same way Windows Explorer does?
Originally, I was sorting using DIR, but then the number format changed.
FOR /f "tokens=*" %%a in ('dir /o:-n /b /ad %SourceFolder%\%SourceFolderMask%*.*.*.*') DO SET "lastFolder=%%~a" & GOTO :foundFolder
All I needed was the newest folder name and with the sort by -n combined with a GOTO, it all worked nicely, until it didn't.
I was able to then use the call to powershell with a custom script file to get what I needed, however, because the list is sorted ascending, I had to make a slight change in my usage.
FOR /f "tokens=*" %%a in ('powershell -Command "C:\_sc\OS\Main\NaturalSort1.ps1; $array = Get-ChildItem -Name -Attribute directory -Path %SourceFolder%;[NaturalSort]::Sort($array)"') DO SET "lastFolder=%%~a"
GOTO :foundFolder
If the ps1 script gets updated to allow reverse sorting, then I can revert back to my previous example of exiting the FOR early with the DO ... & GOTO