How to delete files/subfolders in a specific directory at the command prompt in Windows

1,127,217

Solution 1

You can use this shell script to clean up the folder and files within C:\Temp source:

del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q

Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat

Solution 2

rmdir is my all time favorite command for the job. It works for deleting huge files and folders with subfolders. A backup is not created, so make sure that you have copied your files safely before running this command.

RMDIR "FOLDERNAME" /S /Q

This silently removes the folder and all files and subfolders.

Solution 3

The simplest solution I can think of is removing the whole directory with

RD /S /Q folderPath

Then creating this directory again:

MD folderPath

Solution 4

This will remove the folders and files and leave the folder behind.

pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)

Solution 5

@ECHO OFF

SET THEDIR=path-to-folder

Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A

Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
@ECHO Folder deleted.

EXIT

...deletes all files and folders underneath the given directory, but not the directory itself.

Share:
1,127,217
Deniz Zoeteman
Author by

Deniz Zoeteman

Back-end (web)development. Specialised mostly in PHP.

Updated on July 08, 2022

Comments

  • Deniz Zoeteman
    Deniz Zoeteman almost 2 years

    Say, there is a variable called %pathtofolder%, as it makes it clear it is a full path of a folder.

    I want to delete every single file and subfolder in this directory, but not the directory itself.

    But, there might be an error like 'this file/folder is already in use'... when that happens, it should just continue and skip that file/folder.

    Is there some command for this?