"rm -rf" equivalent for Windows? - windows

I need a way to recursively delete a folder and its children.
Is there a prebuilt tool for this, or do I need to write one?
DEL /S doesn't delete directories.
DELTREE was removed from Windows 2000+

RMDIR or RD if you are using the classic Command Prompt (cmd.exe):
rd /s /q "path"
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
If you are using PowerShell you can use Remove-Item (which is aliased to del, erase, rd, ri, rm and rmdir) and takes a -Recurse argument that can be shorted to -r
rd -r "path"

admin:
takeown /r /f folder
cacls folder /c /G "ADMINNAME":F /T
rmdir /s folder
Works for anything including sys files
EDIT: I actually found the best way which also solves file path too long problem as well:
mkdir \empty
robocopy /mir \empty folder

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

Go to the path and trigger this command.
rd /s /q "FOLDER_NAME"
/s : Removes the specified directory and all subdirectories including any files. Use /s to remove a tree.
/q : Runs rmdir in quiet mode. Deletes directories without confirmation.
/? : Displays help at the command prompt.

You can install cygwin, which has rm as well as ls etc.

For deleting a directory (whether or not it exists) use the following:
if exist myfolder ( rmdir /s/q myfolder )

rm -r -fo <path>
is the closest you can get in Windows PowerShell. It is the abbreviation of
Remove-Item -Recurse -Force -Path <path>
(more details).

The accepted answer is great, but assuming you have Node installed, you can do this much more precisely with the node library "rimraf", which allows globbing patterns. If you use this a lot (I do), just install it globally.
yarn global add rimraf
then, for instance, a pattern I use constantly:
rimraf .\**\node_modules
or for a one-liner that let's you dodge the global install, but which takes slightly longer for the the package dynamic download:
npx rimraf .\**\node_modules

via Powershell
Remove-Item -Recurse -Force "TestDirectory"
via Command Prompt
https://stackoverflow.com/a/35731786/439130

Try this command:
del /s foldername

rmdir /S /Q %DIRNAME%

rmdir /s dirname

First, let’s review what rm -rf does:
C:\Users\ohnob\things>touch stuff.txt
C:\Users\ohnob\things>rm -rf stuff.txt
C:\Users\ohnob\things>mkdir stuff.txt
C:\Users\ohnob\things>rm -rf stuff.txt
C:\Users\ohnob\things>ls -l
total 0
C:\Users\ohnob\things>rm -rf stuff.txt
There are three scenarios where rm -rf is commonly used where it is expected to return 0:
The specified path does not exist.
The specified path exists and is a directory.
The specified path exists and is a file.
I’m going to ignore the whole permissions thing, but nobody uses permissions or tries to deny themselves write access on things in Windows anyways (OK, that’s meant to be a joke…).
First set ERRORLEVEL to 0 and then delete the path only if it exists, using different commands depending on whether or not it is a directory. IF EXIST does not set ERRORLEVEL to 0 if the path does not exist, so setting the ERRORLEVEL to 0 first is necessary to properly detect success in a way that mimics normal rm -rf usage. Guarding the RD with IF EXIST is necessary because RD, unlike rm -f, will throw an error if the target does not exist.
The following script snippet assumes that DELPATH is prequoted. (This is safe when you do something like SET DELPATH=%1. Try putting ECHO %1 in a .cmd and passing it an argument with spaces in it and see what happens for yourself). After the snippet completes, you can check for failure with IF ERRORLEVEL 1.
: # Determine whether we need to invoke DEL or RD or do nothing.
SET DELPATH_DELMETHOD=RD
PUSHD %DELPATH% 2>NUL
IF ERRORLEVEL 1 (SET DELPATH_DELMETHOD=DEL) ELSE (POPD)
IF NOT EXIST %DELPATH% SET DELPATH_DELMETHOD=NOOP
: # Reset ERRORLEVEL so that the last command which
: # otherwise set it does not cause us to falsely detect
: # failure.
CMD /C EXIT 0
IF %DELPATH_DELMETHOD%==DEL DEL /Q %DELPATH%
IF %DELPATH_DELMETHOD%==RD RD /S /Q %DELPATH%
Point is, everything is simpler when the environment just conforms to POSIX. Or if you install a minimal MSYS and just use that.

Here is what you need to do...
Create a batch file with the following line
RMDIR /S %1
Save your batch file as Remove.bat and put it in C:\windows
Create the following registry key
HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)
Launch regedit and update the default value HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)\default
with the following value
"c:\windows\REMOVE.bat" "%1"
Thats it! Now you can right click any directory and use the RMDIR function

LATE BUT IMPORTANT ANSWER to anyone who is having troubles installing npm packages on windows machine and if you are seeing error saying "rm -rf..." command not found.
You can use the bash cli to run rm command on windows.
for npm users, you can change the npm's config to npm config set script-shell "C:\Program Files\Git\bin\bash.exe" this way if the npm package you are trying to install has a post install script that uses rm -rf command, you will be able to run that rm command without needing to change anything in the npm package or disabling the post install scripts config. (For example, styled-components uses rm command in their post install scripts)
If you want to just use the rm command, you can easily use the bash and pass the arguments.
So yes, you can use the 'rm' command on windows.

As a sidenode:
From the linux version with all subdirs (recursive) + force delete
$ rm -rf ./path
to PowerShell
PS> rm -r -fo ./path
which has the close to same params (just seperated) (-fo is needed, since -f could match different other params)
note:
Remove-Item ALIASE
ri
rm
rmdir
del
erase
rd

in powershell, rm is alias of Remove-Item, so remove a file,
rm -R -Fo the_file
is equivalent to
Remove-Item -R -Fo the_file
if you feel comfortable with gnu rm util, you can the rm util by choco package manager on windows.
install gnu utils in powershell using choco:
choco install GnuWin
finally,
rm.exe -rf the_file

You can install GnuWin32 and use *nix commands natively on windows. I install this before I install anything else on a minty fresh copy of windows. :)

Using Powershell 5.1
get-childitem *logs* -path .\ -directory -recurse | remove-item -confirm:$false -recurse -force
Replace logs with the directory name you want to delete.
get-childitem searches for the children directory with the name recursively from current path (.).
remove-item deletes the result.

USE AT YOUR OWN RISK. INFORMATION PROVIDED 'AS IS'. NOT TESTED EXTENSIVELY.
Right-click Windows icon (usually bottom left) > click "Windows PowerShell (Admin)" > use this command (with due care, you can easily delete all your files if you're not careful):
rd -r -include *.* -force somedir
Where somedir is the non-empty directory you want to remove.
Note that with external attached disks, or disks with issues, Windows sometimes behaves odd - it does not error in the delete (or any copy attempt), yet the directory is not deleted (or not copied) as instructed. (I found that in this case, at least for me, the command given by #n_y in his answer will produce errors like 'get-childitem : The file or directory is corrupted and unreadable.' as a result in PowerShell)

In powershell rm -recurse -force works quite well.

here is what worked for me:
Just try decreasing the length of the path.
i.e :: Rename all folders that lead to such a file to smallest possible names. Say one letter names. Go on renaming upwards in the folder hierarchy.
By this u effectively reduce the path length.
Now finally try deleting the file straight away.

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Folder\shell\rmdir\command]
#="cmd.exe /s /c rmdir "%V""

There is also deltree if you're on an older version of windows.
You can learn more about it from here:
SS64: DELTREE - Delete all subfolders and files.

Related

if exist folder rmdir folder && mkdir folder will not execute any command after that &&

What is the syntax that would allow me to delete folder and the create it, regardless of it prior (in)existence?
if exist folder rmdir folder && mkdir folder
Will NOT work. Neither replacing && with &, ||, |...
Which is proper syntax then?
OS: Windows 2012
Shell: cmd.exe*
PS I could accept PS based answers as long as two conditions are met. 1) It have to start from cmd.exe 2) It have to give meaningufull errors to cmd standard output if there are any encountered (like lack of permissions).
Since you are using rmdir without the /S switch I assume the folder of interest is empty, so why removing and recreating it? You could simply create it and suppress the error message in case it already exists, like:
mkdir "folder" 2> nul
This variant maintains all folder attributes and the owner, of course.
If you insist on removing and recreating the folder, use this:
rmdir "folder" 2> nul & mkdir "folder"
This variant destroys all folder attributes and the owner.
In case the folder is not guaranteed to be empty, you need the /S switch for rmdir; also the /Q is useful to avoid being prompted to really remove the folder, like:
rmdir /S /Q "folder" & mkdir "folder"

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I am making a batch script and part of the script is trying to remove a directory and all of its sub-directories. I am getting an intermittent error about a sub-directory not being empty. I read one article about indexing being the culprit. I disabled WSearch but I eventually got the error again. Here's the command:
rmdir /S /Q "C:\<dir>\"
I experienced the same issues as Harry Johnston has mentioned. rmdir /s /q would complain that a directory was not empty even though /s is meant to do the emptying for you! I think it's a bug in Windows, personally.
My workaround is to del everything in the directory before deleting the directory itself:
del /f /s /q mydir 1>nul
rmdir /s /q mydir
(The 1>nul hides the standard output of del because otherwise, it lists every single file it deletes.)
I'm familiar with this problem. The simplest workaround is to conditionally repeat the operation. I've never seen it fail twice in a row - unless there actually is an open file or a permissions issue, obviously!
rd /s /q c:\deleteme
if exist c:\deleteme rd /s /q c:\deleteme
I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:
chkdsk /F e:
This can be run from the search windows box or from a cmd prompt. The /F fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.
enter the Command Prompt as Admin and run
rmdir /s <FOLDER>
I had a similar problem, tried to delete an empty folder via windows explorer. Showed me the not empty error, so I thought I try it via admin cmd, but none of the answers here helped.
After I moved a file into the empty folder. I was able to delete the non empty folder
As #gfullam stated in a comment to #BoffinbraiN's answer, the <dir> you are deleting itself might not be the one which contains files: there might be subdirectories in <dir> that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm from UNIX. rm.exe comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.
Batch script example:
set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"
Im my case i just moved the folder to root directory like so.
move <source directory> c:\
And then ran the command to remove the directory
rmdir c:\<moved directory> /s /q
I had "C:\Users\User Name\OneDrive\Fonts", which was mklink'ed ( /D ) to "C:\Windows\Fonts", and I got the same problem. In my case
cd "C:\Users\User Name\OneDrive"
rd /s Fonts
Y (to confirm the action)
helped me. I hope, that it helps you too ;D
What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...
:Cleanup_Temporary_Files_and_Folders
Erase /F /S /Q C:\MyDir
RMDir /S /Q C:\MyDir
If Exist C:\MyDir GoTo Cleanup_Temporary_Files_and_Folders
The reason rd /s refuses to delete certain files is most likely due to READONLY file attributes on files in the directory.
The proper way to fix this, is to make sure you reset the attributes on all files first:
attrib -r %directory% /s /d
rd /s %directory%
There could be others such as hidden or system files, so if you want to play it safe:
attrib -h -r -s %directory% /s /d
rd /s %directory%
Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.
robocopy - cmd copy utility
/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans
Create en empty dir like this:
mkdir empty
overwrite broken folder with empty like this:
robocopy /copyall /mir /b empty broken
and then delete that folder
rd broken /s
rd empty /s
If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode
one liner:
if exist folder rmdir /Q /S folder
I'm using this in a NPM script like so (Javascript) :
//package.json
"scripts": {
"start": "parcel --no-cache",
"clean": "if exist dist rmdir /Q /S dist",
"deploy": "npm run clean && parcel build --no-source-maps && firebase deploy"
},
Open CMD as administrator
chkdsk c: /F /R
Press the “Y” key if asked to check your disk the next time your system restarts.
Restart the machine. After that just delete the folder.
The easiest way I found to do this is:
rm -rf dir_name
it worked on zsh - macOS, it should work on windows cmd as well.
if you need to delete a folder on Windows with a batch file you will need to use PowerShell and this is how it is done:
rmdir .\directory_name\ -Recurse
Similar to Harry Johnston's answer, I loop until it works.
set dirPath=C:\temp\mytest
:removedir
if exist "%dirPath%" (
rd /s /q "%dirPath%"
goto removedir
)
Force delete the directory (if exists)
Delete.bat
set output_path="C:\Temp\MyFolder"
if exist %output_path% (
echo Deleting %output_path%
attrib -r /s /d %output_path%
rd /s /q %output_path%
)
I've fixed this before my making sure there wasn't extra whitespace in the name of the directory I was deleting. This is more of a concern when I had the directory name contained within a variable that I was passing to RD. If you're specifying your directly in quotes then this isn't helpful, but I hope that someone like me comes along with the same problem and sees this. RD /S /Q can work, as I noticed the issue started happening when I changed something in my batch script.
I can think of the following possible causes:
there are files or subdirectories which need higher permissions
there are files in use, not only by WSearch, but maybe by your virus scanner or anything else
For 1.) you can try runas /user:Administrator in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.
For 2.) download Process Explorer, click Find/Find handle or DLL... or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.

Windows Command Prompt Deleting files in folders

After a backup every file on a disk looks like filename_1.jpg
I am using del *_1.* to delete the file.s But can I use the command in D:\ to work down each folder either?
At present I use del *_1.* then cd .. the cd into the next dir, and so on.
Be very, very careful with this command. One false move and you can do a lot of damage...
First try
dir /b /s "d:\*_1.*"
which should show you a list of target files to check. If you like, you can use "d:\somedirectory\*_1.*" to start at some subdirectory.
Once you're satisfied with your list, the command you want is
del /s "d:\*_1.*"
Which I usually invoke by up-arrowing to return the previous command and editing the DIR /B to DEL to make sure that I don't change the filemask.
But as I say - use with extreme caution! The /s is the magic - it means 'and in subdirectories'

Command to recursively remove all .svn directories on Windows

I have a directory with many sub-directories. In each folder there is a subversion folder (.svn).
Is there a command in windows that will go through each folder and sub-directory and delete the .svn folder?
Or will I have to create a script or do it manually?
Make a litte batch file with the following line and execute it from the parent folder under which there are .svn directories.
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S *.svn*') DO RMDIR /S /Q "%%G"
You can also issue the line below straight from the Command Prompt:
FOR /F "tokens=*" %G IN ('DIR /B /AD /S *.svn*') DO RMDIR /S /Q "%G"
Do this in PowerShell.
NOTE: This is recursive so be sure you are in the right directory!
gci -fil '.svn' -r -force | ri -r -force
Here is the rest of my source tree cleanup script.
gci -fil 'bin' -r -force | ri -r -force
gci -fil 'obj' -r -force | ri -r -force
gci -fil '_ReSharper*' -r -force | ri -r -force
gci -fil '*.suo' -r -force | ri -r -force
gci -fil '*.user' -r -force | ri -r -force
Use the svn export command to export a Subversion working copy into a new "clean" directory structure that doesn't have the .svn directories.
If you want to delete all sub folders named .svn in windows
then create batch file with this content:
for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *.svn') do (
rd /s /q "%%i"
)
save it in a file del_All_Dot_SVN_Folders.cmd . Run it. You're done.
Thanks to http://www.axelscript.com/2008/03/11/delete-all-svn-files-in-windows/
Remember the above code has .svn whereas the code in the link has only *svn so its better
to have the .svn to not accidentally have undesired effect.
Just type .svn in the search box of the File Explorer, then select and delete all search results (see JB Nizet's comment). This method can of course also be used to quickly delete the obj and bin directories, e.g. when organizing svn archives.
Although OP asked for a commandline solution, he also indicated using Windows, and considered a manual deletion, so the File Explorer method could still be considered, especially because it is the fastest method and does not rely on 'tools' like svn export.
Although OP already selected an accepted answer, this answer might still be useful for others. At least it was useful for me, a long time linux / windows user who prefers command lines and first learned about the search box by this post :-)
Sorry for being late to the party but here's another one in a single line:
for /r %i in (.svn) do rmdir /s /q "%i"
I know its too late to answer this but i guess there is an easy way IF have eclipse and the svn plugin installed on your eclipse. Right click on the project, go to Team->disconnect. It will open a popup where you select the first option: 'Also delete the SVN meta-information from file system.' This will remove all the SVN folders automatically along with svn property files that you might forget sometimes while removing .svn folders only!
As an important point, if you want to run shell to delete .svn folders, you may need -depth argument to prevent find command entering the directory that was just deleted and showing silly error messages like e.g.
"find: ./.svn: No such file or directory"
To get rid of this error, you can use the find command as the following:
cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;

Command line tool to delete folder with a specified name recursively in Windows?

I want to delete every "_svn" in every folder and subfolder...
For example
c:\
proyect1
_svn
images
_svn
banner
_svn
buttons
_svn
Then I run something like
rm-recurse c:\proyect1 _svn
And I should get:
c:\
proyect1
images
banner
buttons
The ideal thing would be a tiny stand-alone EXE or something like that.
--
Thanks Grant, as soon as I posted the question I saw SVN documentation about the SVN export command, but I also want to delete the _vti_* folders stuff Visual Studio creates, so I'll also explore the for solution.
Similar to BlackTigerX's "for", I was going to suggest
for /d /r . %d in (_svn) do #if exist "%d" rd /s/q "%d"
Time to learn some PowerShell ;o)
Get-ChildItem -path c:\projet -Include '_svn' -Recurse -force | Remove-Item -force -Recurse
The first part finds each _svn folder recursively. Force is used to find hidden folders.
Second part is used to delete these folders and their contents.
Remove commandlet comes with a handy "whatif" parameter which allows to preview what will be done.
PowerShell is available for Windows XP and Windows Vista. It is present on Windows 7 and on Windows Server 2008 R2 by default.
It's a MS product, it's free, and it rocks!
For inclusion/invocation from within a BATCH file use (say for removing Debug and Release folder):
for /d /r . %%d in (Debug Release) do #if exist "%%d" echo "%%d" && rd /s/q "%%d"
double % are required within a batch file to work as escape chars. Else it reports error of syntax.
Thanks.
for /f "usebackq" %d in (`"dir _svn /ad/b/s"`) do rd /s/q "%d"
http://ebersys.blogspot.com/2008/07/recursively-delete-svn-folders-easy-way.html
In Windows? If you are using tortoiseSVN you can use the export command to export a copy of the project without the .svn/_svn folders.
import os
import shutil
curdir = os.path.abspath(os.path.dirname(__file__))
def removedir(dirname, name = ".svn"):
if os.path.isdir(dirname):
for file in os.listdir(dirname):
if os.path.isdir(os.path.join(dirname, file)) and file == name:
thedir = os.path.join(dirname, name)
shutil.rmtree(thedir)
print ".",
else:
removedir(os.path.join(dirname, file))
I think you can try this Python script, which will work under any OS if you've got Python installed.
Here... with FreeCommander or TotalCommander
http://www.broobles.com/blog/posts/36
socendani
Another option from SVN Forum: use XCopy with a file that contains the list of files/directories to be excluded (.svn or _svn in this case)
XCopy C:\VersionedFolder C:\UnVersionedFolder /EXCLUDE:C:\No.SVN.txt /E /C /I /F /R /Y

Resources