Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I want to delete the whole content of a specified folder on Windows 7 via batch file. My problem is, that 'del' or 'erase' only deletes the files, not the folders and 'rmdir' or 'rd' Always deletes the specified folder with its content, but I only want to delete the content, not the folder itself. I tried the command 'rmdir /S /Q "C:\Share\*"' which gave me a syntax error.

What is the correct way to do this?

I am working on Windows 7 Professional 64-bit and have admin permissions.

share|improve this question

3 Answers 3

up vote 18 down vote accepted

Your batch file will need to run two commands, one to clear out the files then one to remove the child directories. I've assumes the directory you want to clear out is C:\Share\

The batch file should look something like this:

del /s /f /q c:\share\*.*
for /f %%f in ('dir /ad /b c:\share\') do rd /s /q c:\share\%f

del /s /f /q will recursively search through the directory tree deleting any files (even read only files) without prompting for confirmation.

The second line loops through all the sub directories (which should now be empty) and removes them.

Short of deleting the entire folder and recreating it (which I don't think you want to do due to permissions?) this should be the easiest way to clean the folder out.

share|improve this answer
    
If I do a little correction here "for /f %%f" -> "for /f %f" then it works fine :) Thank you very much. –  Michael K Aug 26 '11 at 13:03
4  
del is not necessary. rd/s/q will delete both files and subfolders. –  grawity Aug 26 '11 at 13:51
    
@grawity the del is mainly there for any files in the root folder, could remove the recursion switch though. –  Windos Aug 26 '11 at 19:34
3  
@MichaelK, %%f is for use in batch files, %f for when it's a single command straight to the command line. –  Windos Aug 26 '11 at 19:36
rmdir /s/q C:\Share

You get a "Syntax error" because rmdir only accepts complete names, not wildcards. (In cmd.exe, wildcard expansion is left to the individual programs; not all of them do.)

If you have many directories starting with Share..., use a for loop.

for /d %f in (C:\Share*) do rmdir /s/q "%f"
share|improve this answer
1  
I do not want to delete the share folder. –  Michael K Aug 26 '11 at 13:02

Try this:

c:\> rd /s/q C:\Share
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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