390

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Deniz Zoeteman
  • 9,691
  • 26
  • 70
  • 97
  • Possible duplicate of [What ever happened to deltree, and what's its replacement?](http://stackoverflow.com/questions/338895/what-ever-happened-to-deltree-and-whats-its-replacement) – Rosberg Linhares Feb 16 '17 at 14:35
  • 1
    It is insane how difficult Windows makes deleting folders... Or making one that starts with a dot... Thank god for Bash integration in Windows! `rm -rf path\to\folder` works in Windows 10 (or could come from Git Bash... either way if you have that it's wort a try!) – Stijn de Witt Jan 22 '19 at 09:01

16 Answers16

429

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.

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
Suresh
  • 4,475
  • 1
  • 13
  • 2
  • 86
    This seems to remove the pathtofolder the OP was wanting to keep. – Fuzz Evans Oct 16 '12 at 20:49
  • 5
    This would remove the folder itself, so you'll need to add another command: `md FOLDERNAME` (see answer from @rakoczyn below). – thdoan Aug 18 '15 at 08:32
  • 4
    What do you mean by "backup is created" here? I cannot see anything that would create any kind of backup... – Paul Groke Sep 22 '15 at 18:52
  • 2
    The Directory is not empty Message came as response! – Jamshaid K. Dec 05 '16 at 19:07
  • The behavior can be different on different machines. On one of my machines it gives me "The process cannot access the file..." error and preserves the parent directory, but on another machine there is no error and the parent directory gets deleted. – nightcoder Jan 27 '17 at 22:28
  • 17
    In order not to remove the folder itself, make it the current directory before, then use "." as FOLDERNAME. Re-creating it afterwards is not neccessarily the same because ACLs could be lost. `cd "FOLDERNAME"` `RD . /S /Q` – Moritz Both Jun 19 '17 at 07:20
  • @MoritzBoth Good tip! And don't forget you can chain commands with double ampersand so you could turn this into the much sought for one-liner: `cd "FOLDER" && rd . /S /Q` – Stijn de Witt Jan 22 '19 at 09:04
  • Does this answer address the requirement *"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."*? – Peter Mortensen Sep 14 '19 at 18:21
  • I am really confused and staggered by the fact that wrong answers get so many upvotes in threads, sinking actual answers that do exactly what the OP asked for. Not only is it blatant, but it misleads the google search gang. :\ – IOviSpot Nov 27 '19 at 13:32
  • This is clever, a bit sneaky, a bit dangerous. But it works. It does delete all of the dirs and files in the parent dir. Then, it fails to delete the parent dir since the shell is using it as the working dir. The command displays "The process cannot access the file because it is being used by another process" but returns success status (which seems wrong), but is what I want. For all saying this doesn't work: did you try it? ... And it's not silent (it does show a message) ... Seems that this could change in the future ... if the shell didn't lock the working directory (unix doesn't) – steve Feb 16 '21 at 11:34
  • It's dangerous because if the directory does not exist: the cd command fails and then it deletes all files in current directory – Supertommino May 12 '22 at 07:39
301

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

Community
  • 1
  • 1
Iain
  • 6,392
  • 2
  • 30
  • 50
  • 21
    I tried it but unfortunately files where not deleted, only the sub-folders are deleted. For example I have a folder named Test. It contains 2 folders named as "Ripon" & "Wasim" and it contains a file named as "riponalwasim.txt". The subfolders Ripon and Wasim was deleted but riponalwasim.txt was not deleted. – Ripon Al Wasim Jul 19 '13 at 04:02
  • 19
    Use single percentage sign if you wish to run direct from command line e.g. `%p` – Alex Mar 09 '14 at 08:24
  • 2
    Sad that this takes 2 lines, but at least it works! I'm tired of searching for a working "one-liner" and will go with this one, thanks! – nightcoder Jan 27 '17 at 22:29
  • 3
    You can use the '&&' operator to execute two commands in one line without a bat file (notice single '%' instead of '%%'). del /s /q "myfolder\*" && FOR /D %p IN ("myfolder\*") DO rmdir "%p" /s /q – ravinsp Feb 10 '17 at 07:59
  • could help for the files (just remove that echo) – grenix Mar 14 '17 at 16:04
  • may be an alternative way for deleting directories – grenix Mar 14 '17 at 16:06
  • I use Task Scheduler with this batch file to auto-empty temp folders `%SystemRoot%\temp\*.*` and `%Temp%\*.*` every time I login. Add the **`/F`** switch to the `DEL` command to also force deletion of **read-only files**... ...I also empty the **Recycle Bin** at the same time with `rd /s /q %SystemDrive%\$Recycle.bin`. (If you're concerned about it's icon not updating immediately, Google how to refresh it with `SHEmptyRecycleBin` from `shell32.dll` or see **[this](http://stackoverflow.com/q/9238953/)**.) – ashleedawg May 31 '18 at 06:53
  • 1
    The __DEL__ command line misses option `/A` to delete also files with hidden attribute set and option `/F` to delete also files with read-only attribute set. So `del /A /F /Q "C:\Temp\*"` would be better. And __FOR__ command line should be modified to `for /F "eol=| delims=" %%I in ('dir "C:\Temp\*" /AD /B 2^>nul') do rd /Q /S "C:\Temp\%%I"` because of __FOR__ ignores directories with hidden attribute set. __DIR__ with options `/AD /B` outputs __all__ directories in `C:\Temp` with just their names. – Mofi Jun 02 '18 at 08:35
  • perfect and only solution that works in many different cases. rmdir /s /q . like others stated does not work if the folder is an SVN checkout because it will remove the SVN link too ... This version does not remove the SVN Link – Dominik Lemberger Sep 26 '18 at 12:57
  • subfolders are not deleted – RASMiranda Nov 09 '18 at 09:25
  • Remember to enable [delayed expansion](https://ss64.com/nt/delayedexpansion.html) for the for loop: `setlocal EnableDelayedExpansion` – sonyisda1 Dec 18 '19 at 14:55
94

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

RD /S /Q folderPath

Then creating this directory again:

MD folderPath
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
wojciech_rak
  • 2,276
  • 2
  • 21
  • 30
  • 6
    what if you permission for deleting but not creating new folders?? I hope its possible :) – Sandy Feb 01 '13 at 15:13
  • 14
    This is a bad solution, since it introduces a race on the file system for the directory node, i.e. the second command can fail if executed immediately after. – Rok Strniša Nov 12 '13 at 17:10
  • 27
    Also, bad solution if the directory has special permissions you just nuked *ahem* (whoops) – Immortal Blue Apr 22 '15 at 10:32
  • Don't be put off with the response: 'The directory is not empty.', just issue the command twice :-) – Kieran Ryan Nov 16 '18 at 17:10
  • 2
    RD and RMDIR are the same command and since you posted this answer 9 months after someone stated the same answer, why are people giving you points? – Chizl Mar 26 '19 at 23:00
  • Does this answer address the requirement *"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."*? – Peter Mortensen Sep 14 '19 at 18:22
62

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

pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • 5
    For anyone not sure about this approach: it definitely does not re-create the directory. Without `2>nul`, it outputs "The process cannot access the file because it is being used by another process." – Rok Strniša Nov 12 '13 at 17:28
  • 9
    I hate that Windows cannot delete files and folders being used by some program. And I love that you used that in your favor in this one-liner. – andref Mar 27 '14 at 22:13
  • 2
    So this uber-magic is how we empty a folder in Windows?? Impressive :) – mlvljr Jan 13 '15 at 01:01
  • 3
    @mlvljr Only if you want to keep the parent folder too. `RD /?` will show you the simple way to empty a folder. – foxidrive Jan 13 '15 at 12:22
  • Very impressive (batch files Haskell :) almost) – mlvljr Jan 13 '15 at 20:43
  • 2
    This is nice if you need to come back to your starting location, otherwise simply `CD mypath && RD /S .` would be enough. I don't like that you have to repeat your path twice though, for long paths it becomes hard to read. So I would just add a `set p="mypath"` at the beginning. – Amit Naidu Jul 09 '18 at 18:48
  • Does this answer address the requirement *"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."*? – Peter Mortensen Sep 14 '19 at 18:25
  • This is good, but the second `"%pathtofolder%"` could be replaced with a `.` to shorten things further and keep it DRY. – Jimadine Dec 21 '19 at 18:52
  • As stated, requires pathtofolder to be fully qualified ... since after you cd (pushd), the same relative path does not work. But, as Jamadine says, you can use '.' for the rd. – steve Feb 16 '21 at 11:50
45
@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.

ScottN
  • 1,490
  • 2
  • 20
  • 34
thepip3r
  • 2,855
  • 6
  • 32
  • 38
  • 4
    this should be the right answer.. just make simple.. deletemyfoldercontents.bat file.. pop in your path and it works like a charm.. – timbrown Aug 27 '15 at 17:47
  • 3
    The __DEL__ command line misses option `/A` to delete also files with hidden attribute set and `%dir%\*` should be enclosed in double quotes like `"%dir%\*"` to work also for directories containing a space or one of these characters ``&()[]{}^=;!'+,`~``. And __FOR__ command line should be modified to `for /F "eol=| delims=" %%I in ('dir "%dir%\*" /AD /B 2^>nul') do rd /Q /S "%dir%\%%I"` because of __FOR__ ignores directories with hidden attribute set. __DIR__ with options `/AD /B` outputs __all__ directories with just their names. BTW: `dir` is not a good name for an environment variable. – Mofi Jun 02 '18 at 08:44
  • 1
    does not delete sub folder – RASMiranda Nov 09 '18 at 09:27
  • 1
    @RMiranda, in my tests, it does exactly as the OP asked. Do you have a case where it doesn't delete the subfolders? – thepip3r Nov 13 '18 at 14:57
  • Does this answer address the requirement *"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."*? – Peter Mortensen Sep 14 '19 at 18:26
  • @PeterMortensen Yes, that seems to be the case. I used it on the Temp folder that had files that were in use by other services and it gave an error but skipped on and moved to the next. – ScottN Apr 13 '20 at 21:04
35
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.

Update:

From this useful comment (thanks to Moritz Both), you may add && between, so RMDIR won't run if the CD command fails (e.g. mistyped directory name):

CD [Your_Folder] && RMDIR /S /Q .

From Windows Command-Line Reference:

/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.)

O.Badr
  • 2,853
  • 2
  • 27
  • 36
  • 1
    This is perfect for emptying temp, but that `cd [Your_Folder]` is super critical - I'll have to remember that so I don't delete the directory itself... – sage Oct 15 '15 at 21:56
  • 5
    This is the correct solution. Add `&&` between the commands instead of the line break and you are safe from a failing CD. – Moritz Both Jun 19 '17 at 07:24
  • This is a simple et correct solution. Even works with Azure command shell! – Philippe Nov 16 '17 at 06:35
  • pretty bad solution ... I for example need this command line deletion for a svn update - I want to delete all the files and folders before I make the update svn because there may be some changes on the machine where i use this, but relevant are only the checked in items. Doing RMDIR /S /Q . also removes the SVN link and therefore makes the folder no svn folder anymore – Dominik Lemberger Sep 26 '18 at 12:48
  • How is this different from the previous four answers? – Peter Mortensen Sep 14 '19 at 18:27
15

I use Powershell

Remove-Item c:\scripts\* -recurse

It will remove the contents of the folder, not the folder itself.

rhellem
  • 769
  • 1
  • 11
  • 26
14

None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.


The simple single command line solution which of course can be also used in a batch file:

pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )

This command line contains three commands executed one after the other.

The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.

This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.

PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:

The system cannot find the path specified.

This error message is suppressed by redirecting it with 2>nul to device NUL.

The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.

The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.

Not deleted are:

  1. Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.

  2. Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.

  3. Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.

The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:

The process cannot access the file because it is being used by another process.

File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.

This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.

The third command, POPD, is executed independently of the exit value of command RD.

POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.

Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.

One more interesting fact: I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.

For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.

  • pushd /?
  • popd /?
  • rd /?

Single line with multiple commands using Windows batch file explains the operators && and & used here.


Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"

rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"

rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder

rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"

rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder

rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul

rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

:EndCleanFolder
endlocal

The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.

Important are the two lines:

del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

The command DEL is used to delete all files in the specified directory.

  • The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
  • The option /F is necessary to force deletion of files with the read-only attribute set.
  • The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
  • >nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.
  • 2>nul is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.

The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:

dir "%PathToFolder%\*" /AD /B 2>nul

DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.

The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.

FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.

FOR with option /F ignores empty lines which don't occur here as DIR with option /B does not output empty lines.

FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.

FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.

Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rd /?
  • rem /?
  • set /?
  • setlocal /?
Mofi
  • 46,139
  • 17
  • 80
  • 143
13

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

Example :

RD /S /Q C:/folder_path/here
Sireesh Yarlagadda
  • 12,978
  • 3
  • 74
  • 76
  • 2
    upvoted for being the only one to explain what `/S` and `/Q` mean – SourceVisor Mar 24 '17 at 11:11
  • 3
    No.`rd` is equivalent to `rmdir` and will remove the directory itself and is not what OP wants. – WesternGun Jun 22 '17 at 09:26
  • Does this answer address the requirement "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."? For instance, does it abort completely instead of continuing? – Peter Mortensen Sep 14 '19 at 18:28
11

Use Notepad to create a text document and copy/paste this:

rmdir /s/q "%temp%"
mkdir "%temp%"

Select Save As and file name:

delete_temp.bat

Save as type: All files and click the Save button.

It works on any kind of account (administrator or a standard user). Just run it!

I use a temporary variable in this example, but you can use any other! PS: For Windows OS only!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Filip Gjorgjevikj
  • 1,367
  • 13
  • 11
5

To delete file:

del PATH_TO_FILE

To delete folder with all files in it:

rmdir /s /q PATH_TO_FOLDER

To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:

del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do @rmdir /s /q "%i"
Maxim Suslov
  • 4,335
  • 1
  • 35
  • 29
  • Yes this is correct. Must be two steps. This deserves more upvotes, because it explains why, in comparison with a more voted answer above. – WesternGun Jun 22 '17 at 09:27
  • The __DEL__ command line misses option `/A` to delete also files with hidden attribute set and option `/F` to delete also files with read-only attribute set and double quotes around last argument. So `del /A /F /Q "PATH_TO_FOLDER\*"` would be better. And __FOR__ command line should be modified to `for /F "eol=| delims=" %%I in ('dir "PATH_TO_FOLDER\*" /AD /B 2^>nul') do rd /Q /S "PATH_TO_FOLDER\%%I"` because of __FOR__ ignores directories with hidden attribute set. __DIR__ with options `/AD /B` outputs __all__ directories in `PATH_TO_FOLDER` with just their names. – Mofi Jun 02 '18 at 08:48
  • How is this different from (some of) the previous answers? – Peter Mortensen Sep 14 '19 at 18:29
4

You can do it by using the following command to delete all contents and the parent folder itself:

RMDIR [/S] [/Q] [drive:]path            
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
2

I had following solution that worked for me:

for /R /D %A in (*node_modules*) do rmdir "%A" /S /Q

It removes all node modules folder from current directory and its sub-folders.

This is similar to solutions posted above, but i am still posting this here, just in case someone finds it useful

Tornike Shavishvili
  • 1,244
  • 4
  • 16
  • 35
1
@ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q
Robie Nayak
  • 819
  • 10
  • 18
  • The 2nd line will remove the files in the each file from all the folders in Windows temp directory and the 3rd line cleans up the directories including its contents. – Robie Nayak Jun 06 '17 at 22:41
  • __FOR__ command line should be modified to `for /F "eol=| delims=" %%I in ('dir "%TEMP%\*" /AD /B 2^>nul') do rd /Q /S "%TEMP%\%%I"` because of __FOR__ ignores directories with hidden attribute set. __DIR__ with options `/AD /B` outputs __all__ directories in `%TEMP%` with just their names. – Mofi Jun 02 '18 at 08:51
  • [Documentation for DEL](https://ss64.com/nt/del.html). I think you are on the right track with /F: *"Ignore read-only setting and delete anyway (FORCE) "* – Peter Mortensen Sep 14 '19 at 18:33
1

I tried several of these approaches, but none worked properly.

I found this two-step approach on the site Windows Command Line:

forfiles /P %pathtofolder% /M * /C "cmd /c if @isdir==FALSE del @file"

forfiles /P %pathtofolder%  /M * /C "cmd /c if @isdir==TRUE rmdir /S /Q @file"

It worked exactly as I needed and as specified by the OP.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Haan
  • 101
  • 10
  • The two command lines can be combined to one command line: `forfiles /P "%pathtofolder%" /M * /C "%SystemRoot%\System32\cmd.exe /C if @isdir==FALSE (del /A /F @file) else rd /Q /S @file"` __DEL__ option `/A` is added to delete also files with hidden attribute set as otherwise __DEL__ would output a not found error message for each hidden file in `%pathtofolder%`. __DEL__ option `/F` is added to delete also files with read-only attribute set in `%pathtofolder%` as otherwise __DEL__ would output an access denied error message. – Mofi Jun 02 '18 at 08:23
  • This solution is the slowest of all incomplete solutions posted here because of starting a `cmd.exe` instance for each file and each directory in `%pathtofolder%`. The advantage is that __FORFILES__ does not ignore directories with hidden attribute set as __FOR__ does. – Mofi Jun 02 '18 at 09:00
  • Re *"It worked exactly as I needed and as specified by the OP."*: Did you test for the requirement *"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."*? – Peter Mortensen Sep 14 '19 at 18:38
-14

Use:

del %pathtofolder%\*.*   /s /f  /q

This deletes all files and subfolders in %pathtofolder%, including read-only files, and does not prompt for confirmation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alon
  • 4,862
  • 19
  • 27
  • 9
    Foe me this leaves empty subfolders in %pathtofolder%. – D.H. Dec 15 '11 at 09:29
  • 37
    It does NOT delete subfolders in %pathtofolder%. So bad I have no reputation to vote down this false answer – Vitalii Korsakov Jul 03 '12 at 13:49
  • 1
    As pointed out by Vitalii Korsakov, this deletes all files and files from subdirectories, but leaves the subdirectories in place which the OP asked how to remove as well. – Fuzz Evans Oct 16 '12 at 20:38
  • 6
    Although this command does leave empty folders, it is much closer to what was requested, than the accepted answer. Ofcourse this depands on circumstances. In my case, I would rather have empty folders, than files left in root directory. – MarcusUA Sep 25 '13 at 10:12
  • but how we can delete folders and sub-folder that were open in network share when other client machine open the share drive having write access to that folder.. psfile and net files command will close the file session but again after few seconds it will create automatically another session for that user in server... – user1954762 Jun 24 '16 at 03:08
  • I am not surprised by 44 downvotes, but the 35 upvotes.?? – Gerhard Oct 03 '19 at 06:50