Yikes, the "for loop" stuff is kinda steep. Not going to understand this in the 60 minute I scheduled for it.
Ya, no kiddin'. Make some empty test folders and some that aren't empty, pop one of those lines in a test.bat, and run it from the root of the test folders. Confirm whichever one you like works and just roll with it. I always have to sit there and try deconstructing the FOR crap whenever I run across this because I don't use it myself on a regular basis. I assume you're already hitting up http://ss64.com/nt/for_f.html
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"
for /f "tokens=*" %%d in ('dir /ad/b/s ^| sort /R') do rd "%%d"
for /f "delims=" %%i in ('dir /s /b /ad ^| sort /r') do rd "%%i">NUL
The last one just dumps the output into NUL so it's "quiet", you probably figured that one out. The %%d and %%i can be any letter. The DIR and SORT stuff you can easily figure out. In the top one it's setting "usebackq" to enclose `"dir /ad/b/s | sort /R"` but as you can see in the 3rd example, that's not needed. I'm guessing it was an attempt to handle folders with spaces in the name but it didn't work because it's only if you were specifying a file to read/process from with a space in the path. The only benefit I see is that you don't have to escape the |. It's the tokenizing/delimiting part that's probably jackin' up your brain.
You've probably figured out that the output of DIR and SORT are being "piped" back to FOR to process one line at a time. You could add an additional step before the FOR statement to dump that output into a file and instead have FOR read that file to process; conceptually the same. Each line is being stored in %%d based on the delims or tokens. For the second example, it processes ALL tokens on the line and stores it in %%d. This is why folder names with spaces work on that one. For the others where delims=[null], you explicitly say there are no delimiters on the line and to store the entire thing into %%d. If you don't specify that, well, If you don’t specify delims it will default to "delims=[tab][space]"
. This is why the original example that was missing the ` didn't work with spaces in the folder names since it found a space and stored it into %%d. And, based on the explanation I recently read, the other parts of the line were automatically stored in %%e, %%f, %%g, etc.
And actually, I updated my "examples for the future" based on what I just read up.
for /f "usebackq delims=" %%g in (`"dir /ad/b/s | sort /r"`) do rd "%%g"
for /f "tokens=*" %%g in ('dir /ad/b/s ^| sort /r') do rd "%%g"
for /f "delims=" %%g in ('dir /ad/b/s ^| sort /r') do rd "%%g">NUL
I'd go with either the 2nd or 3rd one if I were using this in a batch file. I don't know if I'd redirect output to NUL or maybe a .log or maybe not care and let it scroll in the console.
If the token/delim stuff was giving you trouble, I hope my blah blah blah was useful.