Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch script to delete everything in a folder except one

I have a script to delete all subfolders and files in a folder:

FOR /D %%i IN ("D:\myfolder\*") DO RD /S /Q "%%i" & DEL /Q "D:\myfolder\*.*"

And it works great! Only problem is that I would like to exclude one or more folders, like the XCOPY exclude feature.

I just cant figure how I could add that to the script.

like image 492
Thomas K Avatar asked Jun 09 '10 18:06

Thomas K


People also ask

How do I delete all files except one in Windows?

Deleting all files in the current Windows command line (DOS) directory, except files with a certain file extension, can best be done with the for command. In the example above, the command is deleting all files in the current directory, except files with the file extension . tiff and . jpg.

What does %1 mean in a batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

How do I select all except one folder?

Select multiple files or folders that are not grouped together. Click the first file or folder, and then press and hold the Ctrl key. While holding Ctrl , click each of the other files or folders you want to select.

What is rmdir in batch file?

Deletes a directory. The rmdir command can also run from the Windows Recovery Console, using different parameters.


1 Answers

You could try to hide the folders before the for-loop, and unhide them afterwards, like this:

ATTRIB +H D:\myfolder\keepit
FOR /D %%i IN ("D:\myfolder\*") DO RD /S /Q "%%i" DEL /Q "D:\myfolder\*.*"
ATTRIB -H D:\myfolder\keepit
like image 163
Patrick Avatar answered Sep 19 '22 14:09

Patrick