3

I want to delete all files and folders in my C:\temp except one specific folder (C:\temp\123) which contains a lot of files and subfolders.

I tried with pushd "c:\temp\123" && rd /s /q "c:\temp" but it deletes all subfolders and files in c:\temp\123.

Can any one please help on the above?

BanksySan
  • 27,362
  • 33
  • 117
  • 216
Romain
  • 61
  • 1
  • 1
  • 9
  • 2
    Use google to [find examples](https://www.google.com/#q=stackoverflow%20batch%20file%20delete%20everything%20except) in a couple of seconds, here's one: [Windows batch script to delete everything in a folder except one](http://stackoverflow.com/a/3009151) – wOxxOm Sep 02 '16 at 11:28
  • 1
    Do you really work with **MS-DOS**, the OS from the 1980s? – aschipfl Sep 02 '16 at 12:26

1 Answers1

11

You could do it the following way:

pushd "C:\Temp" || exit /B 1
for /D %%D in ("*") do (
    if /I not "%%~nxD"=="123" rd /S /Q "%%~D"
)
for %%F in ("*") do (
    del "%%~F"
)
popd

This is very similar to this approach: Batch command to delete everything (sub folders and files) from a folder except one file.

Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99