1

Can someone help me with how to create a batch script that will delete all files/subfolders in a specific folder?

I have tryed this:

set dir="C:\Users\nikola.bakrachevski\Desktop\TEST B"
FOR /D /R %dir% %%X IN (*.tmp) DO RMDIR /S /Q "%%X"
exit
Jeni
  • 918
  • 7
  • 19
  • Also with this FOR D R %dir% %%X IN (*.*) DO RMDIR S Q %%X – Nikola Bakrachevski Apr 28 '20 at 12:12
  • `for %%g in ("C:\Users\nikola.bakrachevski\Desktop\TEST B") do rd /q /s %%g` There is no point in doing a for loop when you could just do rd /q /s. You should ask the question you really want answered. – somebadhat Apr 28 '20 at 23:27

1 Answers1

1

The simplest way to empty a directory, but not the directory itself, is to make it your current directory. You cannot remove the current directory, an error will be output telling you that it cannot be removed because it is being used by another process, (this one). We can simply redirect that error to the NUL device, but the entire content will still be removed, (subject to having the required permissions to do so).

In this example, I used the PushD command to step into the directory to be emptied, (making it current), and step back out, using PopD, (to the directory which was your current directory immediately prior to using PushD).

@Set "dirToEmpty=%UserProfile%\Desktop\TEST B"
@PushD "%dirToEmpty%" 2> NUL && (RD /S /Q "%dirToEmpty%" 2> NUL & PopD)

The && is a special conditional operator which essentially runs a command only if the previous command returned as successful. In this case, I used it so that if, for any reason, stepping into the directory was unsuccessful, no removal would occur.

Compo
  • 36,585
  • 5
  • 27
  • 39
  • This could even be simplified by using `rd /S /Q .`... – aschipfl Apr 28 '20 at 20:14
  • Correct @aschipfl, I made a conscious decision to use the variable in order to ensure absolute clarity on the process. My general preference is not to use a relative path if the path is short and simple enough to reuse, _and I don't want to make my code harder to read, (which is something I am 'occasionally' guilty of)_. – Compo Apr 28 '20 at 23:10
  • Thank you Compo, It works as I need. – Nikola Bakrachevski Apr 29 '20 at 08:54