How to delete files/subfolders in a specific directory at the command prompt in Windows
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?
You can use this shell script to clean up the folder and files within
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
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.
Read more... Read less...
The simplest solution I can think of is removing the whole directory with
RD /S /Q folderPath
Then creating this directory again:
This will remove the folders and files and leave the folder behind.
pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)
@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.
CD [Your_Folder] RMDIR /S /Q .
You'll get an error message, tells you that the RMDIR command can't access the current folder, thus it can't delete it.
CD [Your_Folder] && RMDIR /S /Q .
/S: Deletes a directory tree (the specified directory and all its subdirectories, including all files).
/Q: Specifies quiet mode. Does not prompt for confirmation when deleting a directory tree. (Note that /q works only if /s is specified.)
RD stands for REMOVE Directory.
/S : Delete all files and subfolders in addition to the folder itself. Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
RD /S /Q C:/folder_path/here