0

I am trying to develop a batch file to automatically remove empty folders in Drive D like the code below:

for /d %%d in (*.*) do (
rmdir %%d
)

However, while running the batch file by Windows's job scheduler, I found that the code tried to remove the empty folders into another drive. So how can I change this in coding (*.*) to a specific drive D: ?

Red fx
  • 1,071
  • 2
  • 12
  • 26
Ponomy
  • 13
  • 6
  • Use `for /d %%I in (D:\*) do rmdir "%%I"`. See answer on [Executing BAT files in scheduled task](https://stackoverflow.com/a/41821620/3074564) for details. – Mofi Oct 20 '17 at 08:23
  • 1
    @matsnow: Oh - good editing! Strange how italicised-`.` and `.` look alike. OP: Use `{}` button to hilight code; Text between `*` in narrative *italicises text* Use two `*` instead of one to **bold** text – Magoo Oct 20 '17 at 08:45
  • Given an empty directory, `D:\c\b\a` this may work, however if `D:\c\b` is also empty it would remain because when it was initially parsed it had content, directory `a`. The only way to be sure you'd cleared all of the empty directories using this idea would be to run the routine multiple times in succession. – Compo Oct 20 '17 at 10:26
  • Your code is not checking if the drive is empty before removing it. – Squashman Oct 20 '17 at 14:10

3 Answers3

0

This happens because your script is not executed in drive D: when running via scheduled task, but (by default) in the root folder of the user which executes the task.

Add D: at the beginning of your batch file:

D:
for /d %%d in (*.*) do (
rmdir %%d
)
MatSnow
  • 7,357
  • 3
  • 19
  • 31
0
for /d %%d in (D:*) do (

Note * not .

if you wish, you can use d:\directoryname\* to start the nominated directoryname, or

for /d /r "D:\" %%d in (*) do echo %%d

to proceed through the directory-tree (note: ECHO for safety's sake)

It would be a good idea to use "%%d" for the RMDIR because otherwise directory name containing spaces will be executed as 'remove the directories "directory" "name" "containing" and "spaces"`'

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • 2
    `D:*` does not point to the root of the drive, but `D:\*` does; and I'd use `"%%~d"` (although it makes no difference in this situation, but just in general)... – aschipfl Oct 20 '17 at 08:32
0
@echo off
    setlocal enableextensions disabledelayedexpansion
    for /f "delims=" %%a in ('dir d:\ /s /b /ad ^| sort /r') do 2>nul rmdir "%%~fa"

This uses a dir command to retrieve the list of all folders under the root of drive d:. This list is sorted in reverse order so the child folders appears before its parents. That way if removing a child leaves an empty parent it will also be removed.

This reverse sorted list is processed with a for /f command that tries to remove all the folders. As by default rmdir does not allow removal of non empty folders, only empty folders are removed.

MC ND
  • 69,615
  • 8
  • 84
  • 126