how to delete only empty directories from a batch

2020-07-18 05:54发布

Is there a way to delete all empty sub-directories below a given directory from a batch file?

Or is it possible to recursively copy a directory, but excluding any empty directories?

5条回答
Deceive 欺骗
2楼-- · 2020-07-18 06:02

You really have two questions:

1. Is there a way to delete all empty sub-directories below a given directory from a batch file?

Yes. This one-line DOS batch file works for me. You can pass in an argument for a pattern / root or it will use the current directory.

for /f "delims=" %%d in ('dir /s /b /ad %1 ^| sort /r') do rd "%%d" 2>nul

The reason I use 'dir|sort' is for performance (both 'dir' and 'sort' are fairly fast). It avoids the recursive batch function solution used in one of the other answers which is perfectly valid but can be infuriatingly slow :-(

2. Or is it possible to recursively copy a directory, but excluding any empty directories?

There are a number of ways to do this listed in other answers.

查看更多
太酷不给撩
3楼-- · 2020-07-18 06:11

To copy ignoring empty dirs you can use one of:

robocopy c:\source\ c:\dest\ * /s
xcopy c:\source c:\dest\*.* /s
查看更多
萌系小妹纸
4楼-- · 2020-07-18 06:12

xcopy's /s will ignore blank folder when copying

xcopy * path\to\newfolder /s /q
查看更多
甜甜的少女心
5楼-- · 2020-07-18 06:12

This batch file does the trick just fine from any path, in my case I use Windows Environment variable IWAY61 :

@echo off

cd %IWAY61%

for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"
查看更多
再贱就再见
6楼-- · 2020-07-18 06:20
@echo off
setlocal ENABLEEXTENSIONS
call :rmemptydirs "%~1"
goto:EOF
:rmemptydirs
FOR /D %%A IN ("%~1\*") DO (
    REM recurse into subfolders first...
 call :rmemptydirs "%%~fA"
)
RD "%~f1" >nul 2>&1
goto:EOF

Call with: rmemptydirs.cmd "c:\root dir to delete empty folders in"

查看更多
登录 后发表回答