Delete contents of a directory recursively on Windows - windows

I need to delete the entire contents of a directory (nested folders and all) without deleting the directory itself. Recreating the directory after the fact is not an option as it is being locked by the running process and delete of it would fail.
So far I have the following:
rd /s /q dir1
rd /s /q dir2
rd /s /q dir3
del /q /f *
It works, but the obvious problem is that I have to update this script every time the set of first-level directories changes.
On UNIX, I would solve this like this:
rm -rf *
What is the Windows equivalent?

Assuming that you are executing the command from the top-level directory:
for /d %X in (*.*) do rd /s /q %X
If you are executing this from a script, you must use double percent signs:
for /d %%X in (*.*) do rd /s /q %%X
If you need to delete the files in the top-level directory as well, add this to the script:
del /q /f *

I know this is an old question with an old answer, but I've found a simpler way to do this and thought of sharing it.
You can step into the target directory and use the rd command. Since Windows will not allow you to delete any files or directories currently in use, and you are making use of the target directory by stepping into it, you'll delete all the contents, except the target directory itself.
cd mydir
rd /s /q .
You'll get a message saying:
The process cannot access the file because it is being used by another process.
This will occur when, after deleting all the contents, the rd command fails to delete the current directory, because you're standing in it. But you'll see this is not an actual error if you echo the last exit code, which will be 0.
echo %errorlevel%
0
It's what I'm using and it works fine. I hope this helps.

Related

Remove only files and sub folders from a directory through command prompt

I have a folder named Test in C:\Test path. There are multiple files and folders in this Test folder. Now I want to remove all the contents with in the Test Folder and not delete the Test folder itself.
I have been trying these commands, but it only deletes the files and not folders.
del C:\Test\*
del C:\Test\*.*
I want a single command to delete both files and sub folders from Test.
It is not possible with a single command, but with a single command line.
I would do this:
cd /D "C:\Test" && rd /S /Q "C:\Test"
This first changes into the destination root directory. The && operator lets the following command execute only when the preceding one succeeded. Then the directory and all its contents is attempted to be deleted; for the contents it works fine, but for the root itself, the error The process cannot access the file because it is being used by another process. because of the preceding cd command. This error message (and also others) can be suppressed by appending 2> nul to the rd command:
cd /D "C:\Test" && rd /S /Q "C:\Test" 2> nul
If you want the original working directory to be restored, use pushd/popd rather than cd:
pushd "C:\Test" && (rd /S /Q "C:\Test" 2> nul & popd)
The advantage of this method over deletion and recreation (like rd /S /Q "C:\test" && md "C:\Test") is that the attributes, the owner and the security settings of the root directory are not lost.
Alternatively, you could do the following, which is more complicated but avoids suppression of errors:
del /S /Q "C:\Test\*.*" & for /D %%D in ("C:\Test\*") do #rm /S /Q "%%~D"
This first deletes all files that reside in the root directory, then it loops through all immediate sub-directories and deletes one after another. The root directory itself is never touched.
This is the command which has to be used.
CD "C:/Test" && FOR /D %i IN ("*") DO RD /S /Q "%i" && DEL /Q *.*

Delete files or folder recursively on Windows CMD

How do I delete files or folders recursively on Windows from the command line?
I have found this solution where path we drive on the command line and run this command.
I have given an example with a .svn file extension folder:
for /r %R in (.svn) do if exist %R (rd /s /q "%R")
The other answers didn't work for me, but this did:
del /s /q *.svn
rmdir /s /q *.svn
/q disables Yes/No prompting
/s means delete the file(s) from all subdirectories.
Please execute the following steps:
Open the command prompt
Change directory to the required path
Give the following command
del /S *.svn
You can use this in the bat script:
rd /s /q "c:\folder a"
Now, just change c:\folder a to your folder's location. Quotation is only needed when your folder name contains spaces.
RMDIR path_to_folder /S
ex. RMDIR "C:\tmp" /S
Note that you'll be prompted if you're really going to delete the "C:\tmp" folder. Combining it with /Q switch will remove the folder silently (ex. RMDIR "C:\tmp" /S /Q)
For file deletion, I wrote following simple batch file which deleted all .pdf's recursively:
del /s /q "\\ad1pfrtg001\AppDev\ResultLogs\*.pdf"
del /s /q "\\ad1pfrtg001\Project\AppData\*.pdf"
Even for the local directory we can use it as:
del /s /q "C:\Project\*.pdf"
The same can be applied for directory deletion where we just need to change del with rmdir.
If you want to delete a specific extension recursively, use this:
For /R "C:\Users\Desktop\saleh" %G IN (*.ppt) do del "%G"
Use the Windows rmdir command
That is, rmdir /S /Q C:\Temp
I'm also using the ones below for some years now, flawlessly.
Check out other options with: forfiles /?
Delete SQM/Telemetry in windows folder recursively
forfiles /p %SYSTEMROOT%\system32\LogFiles /s /m *.* /d -1 /c "cmd /c del #file"
Delete windows TMP files recursively
forfiles /p %SYSTEMROOT%\Temp /s /m *.* /d -1 /c "cmd /c del #file"
Delete user TEMP files and folders recursively
forfiles /p %TMP% /s /m *.* /d -1 /c "cmd /c del #file"
For completely wiping a folder with native commands and getting a log on what's been done.
here's an unusual way to do it :
let's assume we want to clear the d:\temp dir
mkdir d:\empty
robocopy /mir d:\empty d:\temp
rmdir d:\empty
You could also do:
del /s /p *.{your extension here}
The /p will prompt you for each found file, if you're nervous about deleting something you shouldn't.
The Windows Command Processor cmd.exe has two internal commands for deletion of files and folders:
The command DEL is for the deletion of files with usage help output on running in a Windows command prompt window either help del or del /?.
The command RMDIR or with shorter name RD is for removal of directories with usage help output on running in a Windows command prompt window either help rmdir or rmdir /? or help rd or rd /?.
Deletion of all *.svn files in an entire folder tree
There can be used in a Windows command prompt window or a Windows batch file the following command to delete really all files of which long or short 8.3 file name is matched by the wildcard pattern *.svn in the directory %USERPROFILE%\Projects or any of its subdirectories:
del /A /F /Q /S "%USERPROFILE%\Projects\*.svn" >nul 2>&1
The usage of option /A to match all files independent on the file attributes replaces the implicit default /A-H to ignore hidden files. So even files with hidden attribute are deleted by this command because of using the option /A. Files matched by wildcard pattern *.svn with hidden attribute set are ignored on not using the option /A.
The option /F forces a deletion of files with file extension .svn which have the read-only attribute set. There would be output the error message Access is denied. if a *.svn file has the read-only attribute set and the option /F is not used on running the command DEL.
The quiet option /Q prevents the user confirmation prompt Are you sure (Y/N)?.
The option /S results in searching not only in the specified directory, but also in all its subdirectories including those with hidden attribute set even on not using option /A for files of which long or short 8.3 name is matched by the wildcard pattern *.svn.
The two redirections >nul and 2>&1 result in redirecting the list of deleted files output to handle STDOUT (standard output) and the error messages output to handle STDERR (standard error) to the device NUL to suppress every output.
There are deleted also hard links and symbolic links matched by the wildcard pattern *.svn on using this command, but not the files linked to on having a file name not ending with .svn or being in a different directory tree.
Files matched by the wildcard pattern *.svn currently opened by a process (program/application) with using shared access permissions to deny all other processes to delete the file as long as being opened by this process are not deleted by this command. File system permissions can result also in files not being deleted by this command.
Deletion of all *.svn folders in an entire folder tree
There can be used in a Windows command prompt window the following command to remove really all folders matching in long or short 8.3 folder name the wildcard pattern *.svn in the directory %USERPROFILE%\Projects and all its subdirectories:
for /F "delims=" %I in ('dir "%USERPROFILE%\Projects\*.svn" /AD /B /S 2^>nul') do #rd /Q /S "%I" 2>nul
The same command line for usage in a batch file containing #echo off at top is:
for /F "delims=" %%I in ('dir "%USERPROFILE%\Projects\*.svn" /AD /B /S 2^>nul') do rd /Q /S "%%I" 2>nul
There is executed on more cmd.exe in background with option /c and the command line specified between ' as additional arguments to run in background the Windows Command Processor internal command DIR to search
in the specified directory %USERPROFILE%\Projects
and in all its subdirectories because of option /S
for just directories because of using the option /AD which includes also junctions and symbolic directory links
matching the wildcard pattern *.svn.
The file system entries (= directory names) matched by these criteria are output in bare format because of option /B with full path because of option /S to handle STDOUT of the background command process without surrounding " even on full directory name containing a space or one of these characters &()[]{}^=;!'+,`~. The error message output by DIR on not finding any name matching these criteria is redirected to device NUL to suppress it.
The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when the Windows Command Processor parses this command line before executing the command FOR which executes the embedded dir command line with using a separate command process started in background.
The output list of directory names with their full paths to handle STDOUT is captured by cmd.exe processing the batch file and processed by FOR after started cmd.exe closed itself.
The FOR /F option delims= defines an empty list of string delimiters which results in each entire directory name is assigned completely one after the other to the specified loop variable I.
The command RD is executed to delete quietly because of option /Q the directory with all files and all subdirectories because of option /S.
There are deleted also junctions (soft links) and symbolic directory links matched by the wildcard pattern *.svn on using this command, but not the directories linked to on having a directory name not ending with .svn or being in a different directory tree.
A directory matched by the wildcard pattern *.svn in which a file is currently opened by a process (program/application) with using shared access permissions to deny all other processes to delete the file as long as being opened by this process is not deleted by this command and of course also no directory above the directory containing the file which cannot be deleted at the moment. File system permissions can result also in directories not being deleted by this command. Windows prevents by default also the deletion of a directory which is the current working directory of any running process.
Other useful information regarding to deletion of files and folders
The directory path %USERPROFILE%\Projects\ can be removed completely or replaced by .\ in the commands above to delete the files and folders matching the wildcard pattern *.svn in the current directory of the Windows Command Processor process which executes the commands.
The directory path %USERPROFILE%\Projects\ can be replaced by %~dp0 to delete the files and folders matching the wildcard pattern *.svn in the directory of the batch file on using the command lines above in a batch file independent on which directory is the current directory on execution of the batch file.
The directory path %USERPROFILE%\Projects\ can be replaced also by a relative path. Please read the Microsoft documentation about Naming Files, Paths, and Namespaces for more details about relative paths.
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 /?
for /?
rd /?
Run mklink /? for help on how to create file and directory links explained very well by MKLink.
See also:
Microsoft documentation for the Windows commands
SS64.com - A-Z index of Windows CMD commands
For hidden files I had to use the following:
DEL /S /Q /A:H Thumbs.db
dir -Recurse *.[extension] |del
dir /b %temp% >temp.list
for /f "delims=" %%a in (temp.list) do call rundll32.exe advpack.dll,DelNodeRunDLL32 "%temp%\%%a"
It worked for me
del /s /q "dir_name"

Windows 7 empty entire directory from command line

I am running a batch file which deploys a war file to a specific directory. However, I want to empty that directory before deploying to it, recursively.
I found this script that is supposed to remove everything in the directory including folders and files but I get this error: "%%i was unexpected at this time."
FOR /D %%i IN ("C:/Program Files (x86)/Apache Software Foundation/Tomcat 6.0/abtapps/ROOT/*") DO RD /S /Q "%%i" DEL /Q "C:/Program Files (x86)/Apache Software Foundation/Tomcat 6.0/abtapps/ROOT/*.*"
I just need a simple way to recursively empty my ROOT directory either by fixing the script above or with another method. Have to be able to do this from a batch file.
I am running windows 7.
SOLUTION
rmdir ROOT /s /q
mkdir ROOT
You should use rmdir /S. Check out this link
I think what you are looking for is to clear the folder not to delete it and recreate it. This will actualy clear the folder so you don't have to recreate it.
CD "C:/Program Files (x86)/Apache Software Foundation/Tomcat 6.0/abtapps/ROOT" && FOR /D %i IN ("*") DO RD /S /Q "%i" && DEL /Q *.*
A few notes.
You only use a single % when running from the command line. doubles are for batch files.
&& is for running multiple commands on the same line.
* The &&'s are especially important in this case because you do not want the del /q . to run if the cd fails as you will delete to contents of what ever directory you started in.
Try this:
forfiles /p "folder" /s /c "cmd /c rd /q #path
replace "folder" with your folder name or drive letter
example: forfiles /p f: /s /c "cmd /c rd /q #path
This will recurse through all subfolders, and only remove the empty folders.
If you use it in command line, you'll get error messages for folders that aren't empty. If you put it in a batch script, it will take some time to run, depending on how many folders you have.

How to delete files recursively

I have the directory structure /foo/bar/fooBar/.. . I want to write a Windows command where I can mention the path till foo directory and it deletes all the files and directory recursively in /foo, but it should NOT delete the foo directory.
I have been using rmdir /q /s [path to foo] but this command deletes the foo directory as well. Let me know if there is any command(s) to accomplish this.
rd /s /q /path/to/foo
md /path/to/foo
del /f /s /q DirectoryWhichContainsFilesToDelete/\*
This will delete all files in the folder DirectoryWhichContainsFilesToDelete without deleting the folder itself.
Have fun :)
I had been scratching my head on this one as well. It is easy enough to create a for loop that uses rmdir however it leaves behind folders that have spaces in the long names. It is possible to manipulate a dir list and get the 8.3 filenames however here is a much simpler solution.
Create an empty folder then;
robocopy \empty_folder \folder_with_sub_folders /PURGE
All subfolders & files will be deleted.
del X /f /s /q
rd X /s /q
this WILL remove the ROOt directory though. make it again with
md X
or make a copy of it first.
otherwise you'll have to do batch funkiness
dir X /ad /b
will give you a list of the immediate subdirectories of X. you can work out the rest
I was looking for a simple command to delete all files in a directory recursively but leaving the directory structure unchanged. So, maybe this could be interesting ;)
for /f "delims=" %i in ('dir /B /S /A:-DH') do #del /F /Q /A:H "%i"
The command 'dir /B /S /A:-D' lists only files (/A:-D) in current directory recursively (/S) without 'dir' summary report (/B). The 'for' loops through each full line (/delims=) and executes the delete command, forced and quiet. I additionally used the hidden flag (/H) both for listing and deletion for some mysterious (e.g. thumbs.db) files.
deltree /foo/* should work fine.
I have used this in a batch file in the past. It uses a for loop to navigate the directory structure.
Here I remove the cvs sub directories off of a tree, needed when copying from one branch to another.
#echo off
if /I exist CVS. rd CVS /s /q >nul
for /F %%z in ('dir cvs /ad /s /b') do echo %%z && rd /s /q %%z
echo Batchfile %0 is complete
Try to use Powershell:
powershell -Command "Remove-Item '\foo\*' -Recurse -Force"
To prevent deleting of the foo directory try change directory to foo prior to the delete such as:
cd c:\foo
rd /s /q c:\foo
This will delete all the files and folders under foo but NOT foo. An error message will be displayed as follow "The process cannot access the file because it is being used by another process."

What ever happened to deltree, and what's its replacement?

In earlier versions of MS-DOS - I want to say version 7, but I could be wrong - there was a deltree command, which recursively deleted all subdirectories and files from a given path.
deltree no longer exists, but del didn't seem to inherit the ability to delete a tree. del /s deletes files, but not folders.
How to you easily (i.e., in one command) delete a tree from a batch file?
As others have mentioned, the rd command has the /s switch to recursively remove sub-directories. You can combine it with the /q switch to forcibly delete a sub-directory (and its contents) without prompting as so
rd /s /q c:\foobar
What everybody is missing is that rd is not an exact replacement for deltree as seemingly (almost) every page returned by Googling for windows deltree would have you believe. The deltree command worked for both directories and files, making it a single convenient, all-purpose deletion command. That is both of the following are valid:
deltree /y c:\foobar
deltree /y c:\baz.txt
However rd (not surprisingly) only works for directories. As such only the first of these commands is valid while the second gives and error and leaves the file un-deleted:
rd /s /q c:\foobar
rd /s /q c:\baz.txt
Further, the del command only works for files, not directories, so only the second command is valid while the first gives an error:
del /f /q c:\foobar
del /f /q c:\baz.txt
There is no built-in way to delete files and directories as could be done with deltree. Using rd and del individually is inconvenient at best because it requires distinguishing whether a file-system object (file-/folder-name) is a file or directory which is not always possible or practical.
You can copy the deltree command from a previous OS, however it will only work on 32-bit versions of Windows since it is a 16-bit DOS command (even in Windows 9x).
Another option is to create a batch-file that calls both del and rd; something like this:
::deltree.bat
#echo off
rd %* 2> nul
del %* 2> nul
You would call it as so:
deltree.bat /s /q /f c:\foobar
deltree.bat /s /q /f c:\baz.txt
This calls both rd and del, passing in the arguments and redirecting the output to nul to avoid the error that one of them will invariably emit.
You will probably want to customize the behavior to accomodate or simplify parameters or allow error messages, but even so, it is not ideal and not a direct replacement for deltree.
An alternative is to get a third-party tool, though finding one is a real exercise in search-query-crafting.
It was replaced with the commands: RMDIR or RD
Delete all subdirectories with /S
Use it quietly with the /Q
Example:
RMDIR /S /Q Folder2Delete
RD /S /Q Folder2Delete
Documentation:
DELTREE at Wikipedia
RMDIR at Wikipedia
RMDIR at Microsoft
Feeling nostalgic, I wrote my own deltree.exe. It works with both directories and files, and uses SHFileOperation() for speed.
https://github.com/ai7/toolbox/tree/master/deltree
deltree v1.01 [Mar 27 2015, 16:31:02] (gcc 4.9.1)
Usage: deltree [options] <path> ...
Options:
-y yes, suppresses prompting for confirmation
-s silent, do not display any progress dialog
-n do nothing, simulate the operation
-f force, no prompting/silent (for rm compatibility)
-r ignored (for rm compatibility)
Delete directories and all the subdirectories and files in it.
It takes wildcards and you can use it like unix rm:
deltree -rf *
rmdir /s /q directory
Nowadays, you can use Powershell to do the same task:
powershell -Command "Remove-Item 'PathToMyDirectory\*' -Recurse -Force"
$ help rd
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory
tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
Actually RMDIR and RD commands in modern Windows operating system merge both the commands RD and Deltree of Win 98 in a single command. It's an internal command that's why you won't find any RD.exe and RMDIR.exe.
By typing this "RD /?" in cmd without double qoutes you'll get exactly what you want.
to delete a directory and all it's contents recursively
rd /s MY_DOOMED_DIR
Use this:
cd (your directory here)
del *.* /f /s /q
Delete all files and subdirectories
cd /d Directory && rd /s /q .\
Others have already posted excellent answers. I regularly use rd /s /q in a command prompt with a for loop to delete directories under the current one: for /d %d in (*) do rd /s /q "%d" (where * can be replaced with names instead, e.g. (dir1 dir2 dirX)

Resources