How can I keep certain subfolders in a directory but remove all other subfolders?

A. I maintain my own documents area and I point My Documents to this location. Many software applications automatically create their own folders in this area that I don't want to maintain. The best method I've found for deleting all folders except for the ones that I've created is to create and run the following script:

@echo off
REM -- Delete everything from a folder except those subfolders listed.
cd \Documents
dir /ad /b > %temp%\folders.list
REM -- Remove from the file those folders that you want to keep.
findstr /x /v "Books" %temp%\folders.list > %temp%\folders1.list
findstr /x /v "Fitness" %temp%\folders1.list > %temp%\folders.list
findstr /x /v "Personal" %temp%\folders.list > %temp%\folders1.list
findstr /x /v "SavillTech" %temp%\folders1.list > %temp%\folders.list
findstr /x /v "Seminars" %temp%\folders.list > %temp%\folders1.list
findstr /x /v "Technical" %temp%\folders1.list > %temp%\folders.list
REM -- Delete all remaining subfolders.
For /f "delims=" %%i in (%temp%\folders.list) do rmdir /s /q "%%i"

The script outputs the names of all subfolders to a file. Next, it uses Findstr to output all lines in that first file that don't match the passed text to a second file that the script uses as input on the next line. Notice that the filenames alternate between folders.list and folders1.list. The reason the filenames alternate is because if you try to use Findstr from within a file to search the file for a certain string and output the names of the subfolders to the same file, you get a blank file. Finally, the script uses the second file as input to a For loop that removes each subdirectory left in the first file. Be aware that in my example, the final file that the script creates is folders.list. However, if you want to keep an odd number of folders, your final file would be folders1.list, which you would then use instead of folders.list as the input to the For loop. Failure to specify the correct output file will remove subfolders that you didn't intend to remove.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.