Goal: Delete empty folders at end of a mutli-step clean-up. rd without "Force" removes directories that are not empty.

This works:

for /f "usebackq" %%d in (`"dir O:\Folder~1\Folder /ad/b/s | sort /R"`) do rd "%%d"

These don't work:

for /f "usebackq" %%d in (`"dir \"O:\Folder With Spaces\Folder\" /ad/b/s | sort /R"`) do rd "%%d"
for /f "usebackq" %%d in (`"dir ""O:\Folder With Spaces\Folder"" /ad/b/s | sort /R"`) do rd "%%d"
for /f "usebackq" %%d in (`"dir ^"O:\Folder With Spaces\Folder^" /ad/b/s | sort /R"`) do rd "%%d"

I know I'm missing something simple...

Adding the example below to the mix:
enter image description here

If I actually echo the %d it echos.... "O:\Patient". Not the full name.

2 Answers 2


You don't need the (outer) double quotes with usebackq.

You can get the list of directories from your piped commands, but when the output has spaces, only the first part will go to the %%d variable. To avoid that, use an additional tokens=* parameter (from for /?):

for /f "usebackq tokens=*" %%d in (`dir "C:\Program Files" /ad /b /s ^| sort /R`) do echo "%%d"

You need to escape the pipe character:

FOR /F "usebackq" %i IN (`dir /b ^| sort`) DO echo %i
  • Updated question with an example. The pipe isn't an issue (Actually removed it since the sort is kinda unneeded). The issue is the quotes within quotes.
    – WernerCD
    Oct 5, 2011 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.