"rm -rf" equivalent for Windows?
Asked Answered
E

24

710

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+

Expostulation answered 18/9, 2008 at 23:8 Comment(1)
TLDR: use rmdir /S /QIlluminative
D
969

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"
Doublepark answered 18/9, 2008 at 23:11 Comment(15)
It's worth pointing out that for large numbers of files, rmdir /s /q is typically significantly faster than the equivalent "select dir, shift + delete" operation in explorer.Imbibe
How about using flags to match directory names? If I want to drop all directories under foo\, rmdir /s /q foo\* gives an error for syntax incorrect.Premonition
This doesn't delete files, like rm -rf does, and it also returns a non-zero value when the directory doesn't exist, so rd /s /q foo && echo "yay" will fail if directory "foo" doesn't exist.Alternately
@Derek, Doskey could help you create aliases for ls=dir: devblog.point2.com/2010/05/14/…Nitaniter
What if dir. not empty and some files get Access is denied and others The process cannot access the file because it is being used by another process?Figment
I just tried this in seven and you need to do /S and /Q (caps)Lithophyte
Mystified here. I know that I tried this command and it did not work if there were files in the directory tree; now I go back and . . . magically it seems to work. Does anyone else experience inconsistent behavior with this?!Antiknock
Yes, I experience inconsistent behavior all the time. It says it cannot delete the directory because it is blocked by some process. But there are no processes blocking the directory.Himyarite
Use if exist myfolder ( rmdir /s/q myfolder ) if you don't know whether the folder will exist or notSecrest
This doesn't seem to work in PowerShell? I'm getting "A positional parameter cannot be found that accepts argument '/q'."Alikee
@JonGunter for Powershell you use the Remove-Item cmdlet msdn.microsoft.com/en-us/powershell/reference/5.1/…Doublepark
Maybe it worked in some older windows. But now it does not work at all.T
help rmdir in windows 7 indicates /S should be used to remove the whole directory tree and /Q should be used for quiet mode.Fondea
The system cannot find the path specified :CDoddering
It's also worth pointing out the saying rd -r out loud makes you sound like a pirate.Bedfellow
O
172

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
Octillion answered 18/9, 2008 at 23:41 Comment(7)
My hero! And one tip: You create your empty folder at C:\empty, then once inside each crazy folder, one can just do robocopy /mir c:\empty .Cheep
The takeown helped me as I copied folder from Linux system with rsync by mistake and I had no privileges to remove that folder... Not even the robocopy worked. ThanksKeystroke
Very nice answer. It works. (all other answers on the page don't). But cacls is deprecated. Is it possible to make a contemporary answer, please? The second variant already works and is not deprecated.T
This doesn't do anything for me. Could someone please explain how it is supposed to work? (robocopy) - It might delete contents of folders, but not folders themselvesPhylogeny
@Octillion when I run cacls "C:\B" /c /G "ADMINNAME":F /T I get No mapping between account names and security IDs was done.Berger
@bilal substitute"adminname" with your actual account name.Octillion
@Octillion For me rmdir was not working because few files were having long paths, actually your solution of copying empty folder to folder is a smart solution, thank youBruckner
O
135

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

Orcein answered 18/9, 2008 at 23:13 Comment(5)
Simplest, perfect answer to the question. Should be the accepted one.Recoil
@Artif3x: It's the equivalent of rm -r not rm -rfWaters
@joshua The adding of the /q does the same thing a the -f, so i'm not sure what you mean.Recoil
@Artif3x: Not so. -f will remove a file for which you don't have write permissions. rmdir /Q won't.Waters
Ah, I understand. The OP didn't say anything about not owning the files, but that's a good addition, as someone else added: takeown /f <folder_path> /r /d yRecoil
I
28

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.

Insomnia answered 1/3, 2016 at 19:32 Comment(0)
B
22

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

Bekelja answered 18/9, 2008 at 23:14 Comment(0)
O
21
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).

Obscuration answered 4/9, 2020 at 17:20 Comment(1)
THANK YOU! This suggestion actually worked in Windows Terminal.Headpin
S
18

For deleting a directory (whether or not it exists) use the following:

if exist myfolder ( rmdir /s/q myfolder )
Secrest answered 1/6, 2016 at 19:59 Comment(1)
Actually this is the answer. Thanks @SecrestSpermary
R
12

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
Recoil answered 1/3, 2019 at 15:27 Comment(1)
A solid solution to the problem as it's OS-agnostic.Lohner
B
10

via Powershell

 Remove-Item -Recurse -Force "TestDirectory"

via Command Prompt

https://mcmap.net/q/56117/-quot-rm-rf-quot-equivalent-for-windows

Beadroll answered 19/12, 2018 at 21:8 Comment(0)
Z
7

Try this command:

del /s foldername
Zymogenesis answered 18/9, 2008 at 23:11 Comment(1)
worked for me in combination w/ rmdir /s /q as some files were locked and rmdir would fail on those. del / foldername nuked the locked files which then allowed rmdir to get rid of root dir. Nice.Germain
C
7

rmdir /S /Q %DIRNAME%

Colfin answered 18/9, 2008 at 23:12 Comment(0)
C
4

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:

  1. The specified path does not exist.
  2. The specified path exists and is a directory.
  3. 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.

Coastguardsman answered 21/4, 2015 at 17:40 Comment(0)
H
4

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
Hampshire answered 13/7, 2021 at 21:13 Comment(0)
I
4

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
Ish answered 1/10, 2021 at 13:4 Comment(0)
S
3

rmdir /s dirname

Sepulveda answered 18/9, 2008 at 23:10 Comment(0)
E
3

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

Eclecticism answered 4/9, 2012 at 1:55 Comment(1)
This is a great start, but the batch file is not needed: cmd.exe /s /c rmdir "%V" is enoughConvenience
M
3

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.

Milkwhite answered 5/4, 2020 at 18:17 Comment(1)
This solution will add .npmrc globally. You can undo the solution with npm config delete script-shell to get back as default. If you want the solution to be only local, use: npm config set script-shell "C:\Program Files\Git\bin\bash.exe" --userconfig .npmrc This will add the .npmrc file to your current directory.Prolong
C
3

In powershell rm -recurse -force works quite well.

Conformist answered 9/7, 2021 at 10:48 Comment(2)
rm is just (one of the plenty del, erase, rd, ri, rm, rmdir) aliases for remove-item wich is already mentioned in answers https://mcmap.net/q/56117/-quot-rm-rf-quot-equivalent-for-windows and https://mcmap.net/q/56117/-quot-rm-rf-quot-equivalent-for-windows and the accepted answer https://mcmap.net/q/56117/-quot-rm-rf-quot-equivalent-for-windows (which does not explicitly state to use force though - but all the others do)Gynecology
Well -Force makes a difference. I found the other answers confusing.Conformist
E
2

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

Eudemonics answered 19/9, 2008 at 0:3 Comment(0)
D
2

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.

Doubletree answered 3/9, 2018 at 6:57 Comment(0)
R
2

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)

Rumen answered 12/6, 2019 at 23:16 Comment(0)
J
0

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.

Joinville answered 25/3, 2015 at 13:1 Comment(0)
C
-1

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\rmdir\command]
@="cmd.exe /s /c rmdir "%V""

Convenience answered 22/7, 2021 at 7:42 Comment(0)
A
-3

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.

Arbogast answered 18/9, 2008 at 23:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.