David Brierton
David Brierton

Reputation: 7397

Deleting Folder Contents but not the folder

I have a folder C:\Epson Scans, I am trying to figure out how to write a script that will delete the contents of the folder but leave the folder intact. I have figured out how to delete the entire folder and I could recreate it. But I wanted to know if anyone knows a way of just deleting the contents inside the folder and not actually deleting the folder. Any help with this would be greatly appreciated!

Edit: Inserting working code so I can loop through many computers and do it at once. Will someone please tell me why the code is not working where I have inserted it?

@echo off
setlocal enabledelayedexpansion
set Delete_success=0
set total=0

for /F %%G in (pclist.txt) do ( 
    set /a total+=1


pushd "C:\Epson Scans" || exit /B 1
for /D %%I in ("*") do (
    rd /S /Q "%%~I"
)
del /Q "*"
popd

if !ERRORLEVEL!==0 (
        set /a Delete_success+=1
    ) else (
        echo EpsonDelete copy failed on %%G>>EpsonDelete_FailedPCs.txt
    )

)
echo Delete Success: %Delete_success%/%total% >>EpsonDelete_FileCopy.txt

Upvotes: 3

Views: 4538

Answers (3)

aschipfl
aschipfl

Reputation: 34909

del deletes files only, so del /S /Q "C:\Epson Scans" deletes all files in the given folder and sub-folders (due to /S).

rmdir deletes folders, so specifying rmdir /S /Q "C:\Epson Scans" also deletes the folder Epson Scans itself.

Of course you could execute mkdir "C:\Epson Scans" afterwards to newly create the deleted folder again1, but this was not asked for. So the correct answer is to use a for /D loop over C:\Epson Scans and delete each folder it contains, and then use del /Q to delete the files:

pushd "C:\Epson Scans" || exit /B 1
for /D %%I in ("*") do (
    rd /S /Q "%%~I"
)
del /Q "*"
popd

Note that rd is the same as rmdir -- see also this post: What is the difference between MD and MKDIR batch command?

1) Regard that some folder attributes get lost if you do that, for example the owner. Also the case is lost as Windows treats paths case-insensitively.

Upvotes: 8

TTomer
TTomer

Reputation: 356

del C:\Epson Scans*.* if this is batch file you might want to add /Q in order to avoid a delete confirmation dialog:

del C:\Epson Scans\*.* /Q

Upvotes: 0

Harry Birimirski
Harry Birimirski

Reputation: 1028

del /S C:\Epson Scans*
(use S to delete all files and folders in selected folder)

Upvotes: 0

Related Questions