125

I need a Windows command to delete a directory and all its containing files but I do not want to see any errors if the directory does not exist.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jaywayco
  • 5,846
  • 6
  • 25
  • 40

5 Answers5

115

Redirect the output of the del command to nul. Note the 2, to indicate error output should be redirected. See also this question, and especially the tech doc Using command redirection operators.

del {whateveroptions} 2>null

Or you can check for file existence before calling del:

if exist c:\folder\file del c:\folder\file

Note that you can use if exist c:\folder\ (with the trailing \) to check if c:\folder is indeed a folder and not a file.

Čamo
  • 3,863
  • 13
  • 62
  • 114
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
73

Either redirect stderr to nul

rd /q /s "c:\yourFolder" 2>nul

Or verify that folder exists before deleting. Note that the trailing \ is critical in the IF condition.

if exist "c:\yourFolder\" rd /q /s "c:\yourFolder"
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • 18
    @GolezTrol - Neither of you deleted the folder as requested by the OP. Both of you focused on deleting a file. – dbenham Jan 24 '13 at 15:38
40

For me on Windows 10 the following is working great:

if exist <path> rmdir <path> /q /s

q stands for "delete without asking" and s stands for "delete all subfolders and files in it".

And you can also concatinate the command:

(if exist <path> rmdir <path> /q /s) && <some other command that executes after deleting>
toddeTV
  • 1,447
  • 3
  • 20
  • 36
2

You can redirect stderr to nul

del filethatdoesntexist.txt 2>nul
Bali C
  • 30,582
  • 35
  • 123
  • 152
  • 2
    Did you try this? This doesn't work. If it doesn't exist, I still see the error – dgo Jul 27 '17 at 00:42
0

The above comes up with Y or N in the prompt. So, I used the following instead and it works perfectly.

if exist cddd rmdir cddd

Hope this helps someone.

Cheers.

Anjana Silva
  • 8,353
  • 4
  • 51
  • 54
  • To avoid the prompt you have to add __/Q__ to the rmdir command. If you need to remove all files and subdirectories you need also __/S__. You didn't see the prompt probably because the directory was not there. – Bemipefe Jan 21 '20 at 13:12