How to delete empty folders using windows command prompt?
Asked Answered
M

17

98

I need to delete all empty folders from my application folder using windows command prompt?

How can I create a bat file like that?

Please help me.

Maryammaryann answered 20/10, 2011 at 4:51 Comment(0)
S
59
for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

from: http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx

Of course I'd test it first without deleting before I do that command. Also, here's a modded version from the comments that includes folders with spaces:

 for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

P.S. there are more comments in the blog post that might help you out so be sure to read those too before you try this out

Sectional answered 20/10, 2011 at 4:55 Comment(10)
I like this one. The link here mentions that this one is easier (similar to the one below): for /f "tokens=*" %%d in ('dir /ad/b/s ^| sort /R') do rd "%%d"Readytowear
Where do you put path to folders?Cyst
@Cyst I had this question too. I can't figure out how to post backquotes in the comments, but I'm using ([backquote]dir /ad/b/s "c:\path"[backquote])Henriques
If you don't use the line above in a batch file then you need to replace %%d with %dOverturn
It can be done easily using ROBOCOPY. See my answer below for details.Intubate
Look at https://mcmap.net/q/218602/-add-39-delete-empty-folders-39-to-windows-context-menu to find out how to add this functionality to context menu.Hightoned
That's a weird way of using a quoted text command. But I suppose it's a way of dealing with the pipe...Federation
FYI this method deletes Directory Junctions even if what they point to is not empty...Had
Running this tried to execute a program in one of the subdirectories...Comeau
To avoid the "The directory is not empty." error message(s), you can redirect them to nul, by adding 2>nulSouthernmost
I
161

You can use the ROBOCOPY command. It is very simple and can also be used to delete empty folders inside large hierarchy.

ROBOCOPY folder1 folder1 /S /MOVE

Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other(required) files to different folder. /S option is to skip copying(moving - in the above case) empty folders. It is also faster as the files are moved inside the same drive.

Intubate answered 9/5, 2015 at 10:44 Comment(13)
OK, this seems great and works! I just don't understand why, if running the cmd from inside the project folder, its giving me "ERROR 32 (0x00000020) Deleting Source Directory" - meaning it can't delete the main directory! Thank god it can't delete it because is not supposed to - its not empty! ("The process cannot access the file because it is being used by another process." - where file must be the dir). I'm running inside it with: robocopy . . /s /move.Loupe
@PedroReis According to me, you are getting this error as you are trying to delete/move it while the child file/folder is still open. If you need more help, I think it is better to post it as a new question so that others who are facing this issue can find your question and resolve their issue.Intubate
@VarunSharma I now see that the issue may be that ROBOCOPY is really moving folder1 into folder1; it is not doing the smart thing of checking that if it is for the same position then don't move it at all!; and is really deleting and creating it again. Nevertheless, it does delete the empty folders anyway even with this error... (a bit strange, but it is what I want)Loupe
@PedroReis Actually, it does not delete and create files. It just changes the address since it is done inside same drive. Try this. ROBOCOPY a 2+ GB file and you can see that it takes less than 2 seconds. It can do this at such speed as it is not actually moving any files but changing file's address in drive file system table. I am not sure if it even changes address and it might just check the address. It takes time only if you are creating copies of files or moving files to different drive.Intubate
Robocopy looks like a tempting and simple solution, but it fails to deal with nested empty folders. If you have an empty folder inside an empty folder, you would have to run the Robocopy script twice to remove both. if you have 3 or 4 nested folders then you'll have to run it 3 or 4 times.Linter
@ss64 I just now tested ROBOCOPY with nested empty folders and it successfully deleted even nested empty folders in a SINGLE run.Intubate
I just tested this again on Windows 10 it definitely fails to work in a single run for me. It may be a version specific thing or perhaps the alphabetic order of the folder names.Linter
example for comparison md demo cd demo md aa md bb cd aa md sub1 cd .. cd.. robocopy demo demo /s/move result bb and sub1 are deleted but aa is notLinter
@ss64 I tested again for your example and it worked perfectly for me in Win 7. As you said, it might be due to some version issue. It might also happen if any hidden files ( like Thumbs.db ) is generated in the folder you are trying to delete. Just to confirm, once check if any hidden file is present (by un-hiding hidden system files).Intubate
@VarunSharma So I tested again, first attempt it deleted everything in one run as you say. I then tried the exact same script again and it failed to delete some folders. There are no hidden or system files present. Experimenting a few times it seems that opening the folder in explorer just once is enough to make the difference, I didnt leave explorer focussed on any of the folders to be deleted, however if I view the folder and then exit explorer completely they will delete in one pass. That would seem like it's a Win10/Explorer issue, but if I delete using RD this never happens!Linter
This works great but fails on subdirectories with a "thumbs.db" or any hidden file for that matter. Took me a few minutes to figure out. Easily fixed with a del folder1\thumbs.db /s before doing the robocopy.Crider
AmI correct in thinking folder names with spaces need to be enclosed in double quotes, and backslashes in path names need to be replaced with double backslashes?Feuchtwanger
@RayWoodcock Yes. You're right. Folder names with spaces need to be enclosed in double quotes. AFAIK, you cannot use backslashes in Windows folder names.Intubate
S
64

A simpler way is to do xcopy to make a copy of the entire directory structure using /s switch. help for /s says Copies directories and subdirectories except empty ones.

xcopy dirA dirB /S

where dirA is source with Empty folders. DirB will be the copy without empty folders

Schnorr answered 7/2, 2013 at 3:3 Comment(6)
This should be the accepted answer. Nice and simple! Thanks!Saphra
Adding the /I switch, e.g. xcopy dirA dirB /SI will skip the prompt that says "Does dirB specify a file name or directory name on the target?"Abdias
I agree this is simple, but I have a directory structure with over 1TB of data. I don't want to replicate that!Underthecounter
You could do something similar with RoboCopy and not copy empty folders. I suppose useful if you are copying data, but not if you want to prune empty folders.Changeable
Also be aware that this doesn't copy hidden and system files - include the /h flag for thatSpagyric
@JYelton, in that case, use the /T /E options to copy folder structure without copying filesSubplot
S
59
for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

from: http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx

Of course I'd test it first without deleting before I do that command. Also, here's a modded version from the comments that includes folders with spaces:

 for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

P.S. there are more comments in the blog post that might help you out so be sure to read those too before you try this out

Sectional answered 20/10, 2011 at 4:55 Comment(10)
I like this one. The link here mentions that this one is easier (similar to the one below): for /f "tokens=*" %%d in ('dir /ad/b/s ^| sort /R') do rd "%%d"Readytowear
Where do you put path to folders?Cyst
@Cyst I had this question too. I can't figure out how to post backquotes in the comments, but I'm using ([backquote]dir /ad/b/s "c:\path"[backquote])Henriques
If you don't use the line above in a batch file then you need to replace %%d with %dOverturn
It can be done easily using ROBOCOPY. See my answer below for details.Intubate
Look at https://mcmap.net/q/218602/-add-39-delete-empty-folders-39-to-windows-context-menu to find out how to add this functionality to context menu.Hightoned
That's a weird way of using a quoted text command. But I suppose it's a way of dealing with the pipe...Federation
FYI this method deletes Directory Junctions even if what they point to is not empty...Had
Running this tried to execute a program in one of the subdirectories...Comeau
To avoid the "The directory is not empty." error message(s), you can redirect them to nul, by adding 2>nulSouthernmost
T
17

You don't need usebackq:

FOR /F delims^= %%A IN ('DIR/AD/B/S^|SORT/R') DO RD "%%A"
Tingly answered 11/4, 2013 at 16:51 Comment(2)
Thanks Tom... you are right. however in a command line it would actually be using a single % opposite to a batch file. Users: note that RD does not delete files nor directory containing files. simply empty directories. So it's totally safe. FOR /F delims^= %A IN ('DIR/AD/B/S^|SORT/R') DO RD "%A"Commons
If you are using cygwin, make sure you check your path order, or explicitly point SORT to the dos version.Changeable
E
8

Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736

Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

or, more tersely,

gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri

credit goes to the posting author

Everick answered 8/10, 2013 at 5:11 Comment(0)
O
5

from the command line: for /R /D %1 in (*) do rd "%1"

in a batch file for /R /D %%1 in (*) do rd "%%1"

I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.

Opsonize answered 4/10, 2015 at 19:22 Comment(0)
S
3

This is a hybird of the above. It removes ALL files older than X days and removes any empty folders for the given path. To use simply set the days, folderpath and drive

@echo off
SETLOCAL
set days=30
set folderpath=E:\TEST\
set drive=E:

::Delete files
forfiles -p %folderpath% -s -d -%days% -c "cmd /c del /q @path "

::Delete folders
cd %folderpath%
%drive%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"`
Soong answered 27/5, 2015 at 11:2 Comment(1)
good one but i have to remove apostrof at the end of last line for /f "usebackq delims=" %%d in ("dir /ad/b/s | sort /R") do rd "%%d"Delores
D
3

It will be worked fine. This is best way to delete old files and remove empty directories recursively. following .bat file is,

forfiles /p [PATH] /s /m [FILE-PATTERN] /d -[DAYS] /c "cmd /c del @path"
for /f "delims=" %%d in ('dir [PATH] /s /b /ad ^| sort /r') do rd "%%d"

The placeholders needs to be replaced as follows (without the quotation marks):

[DAYS] = Max. age of the files in days, e.g. “10”
[PATH] = Path to search for old files and empty folders, e.g. “C:\Backup\”
[FILE-PATTERN] = Pattern that matches files to delete, e.g. “*.bkp”

The script has been successfully tested under Windows 7 and Windows Server 2003.

Decontaminate answered 7/10, 2017 at 6:20 Comment(0)
C
2

Install any UNIX interpreter for windows (Cygwin or Git Bash) and run the cmd:

find /path/to/directory -empty -type d

To find them

find /path/to/directory -empty -type d -delete

To delete them

(not really using the windows cmd prompt but it's easy and took few seconds to run)

Camenae answered 2/6, 2016 at 6:5 Comment(2)
Plus ten for including how to just find them.Merri
In my version of find the first command works, but when adding -delete it says "invalid predicate -delete"Largeminded
D
1

A more modern and easier solution is:

forfiles /p C:\Path\To\Folder /c "cmd /c if @isdir==TRUE rd @file"

This will attempt to execute rd on all the directories located in C:\Path\To\Folder. Directories that have content in them will not be deleted.

If you exclude /p C:\Path\To\Folder then it'll run in the current directory.

If you add /s (before the /c) then it'll also look in sub-directories.

Demonography answered 5/3, 2022 at 17:59 Comment(0)
S
0
@echo off
set /p "ipa= ENTER FOLDER NAME TO DELETE> "
set ipad="%ipa%"
IF not EXIST %ipad% GOTO notfound
IF EXIST %ipad% GOTO found
:found
echo DONOT CLOSE THIS WINDOW
md ccooppyy
xcopy %ipad%\*.* ccooppyy /s > NUL
rd %ipad% /s /q
ren ccooppyy %ipad%
cls
echo SUCCESS, PRESS ANY KEY TO EXIT
pause > NUL
exit 
:notfound
echo I COULDN'T FIND THE FOLDER %ipad%
pause
exit
Sackman answered 15/3, 2017 at 13:1 Comment(0)
M
0

If you want to use Varun's ROBOCOPY command line in the Explorer context menu (i.e. right-click) here is a Windows registry import. I tried adding this as a comment to his answer, but the inline markup wasn't feasible.

I've tested this on my own Windows 10 PC, but use at your own risk. It will open a new command prompt, run the command, and pause so you can see the output.

  1. Copy into a new text file:

    Windows Registry Editor Version 5.00

    [HKEY_CURRENT_USER\Software\Classes\directory\Background\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"

    [HKEY_CURRENT_USER\Software\Classes\directory\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"

  2. Rename the .txt extension to .reg

  3. Double click to import.
Mme answered 10/2, 2020 at 23:27 Comment(0)
Q
0
for /r "D:\Music" /d %F in (.) do @dir /b "%F" | findstr "^" >nul || rmdir %~fF

D:\Fun is the folder that contains empty folders double quotation in the case of space in folder name (no need in this example)

Quintillion answered 20/11, 2021 at 12:47 Comment(0)
B
0

The following .cmd is an experiment (that works) to:

  • Deletes empty directories and included "Old"(-1days) files under %temp% & C:\Windows\Temp folders,
  • makes an cmd output log to a .txt file, about fouded & deleted folders/files .

%temp% = C:\Users(user)\AppData\Local\Temp | %userprofile%\AppData\Local\Temp

code:

::  This is a .cmd file
::    Use to:
::        Writes a Log about Temporary files & folders.
::        Cleans 'Windows Temp' folders/files.    (%userprofile%\AppData\Local\Temp  -&-  %windir%\Temp)
::        - a 'Cleaning_LOGs.txt'  will be created or updated in  Documents Library.    (%userprofile%\Documents\Cleaning_LOGs.txt)
::        
@echo off
title Log&CleanTemp

: Set the Path of 'Log file'  (%LogPath% variable)
set "LogPath=%userprofile%\Documents\Cleaning_LOGs.txt"
::  Note: ">> path\file.txt 2>&1" redirects cmd output to <path\to>\<log_file.txt>,    (will be created if does not exist)
::        (if exist, adds the new log at the end of the file, without deleting previous logs)

: Set  'C:\Windows\Temp'  (%WinTemp% var.)
set "WinTemp=%windir%\Temp"

: Seperator [Header] with Date-Time between (any) previous Logs in <log_file.txt>
echo: >> %LogPath% 2>&1
echo ======================================== >> %LogPath% 2>&1
echo %date% - %time% >> %LogPath% 2>&1
echo: >> %LogPath% 2>&1
echo Log Path: %LogPath%  (this text file) >> %LogPath% 2>&1
echo: >> %LogPath% 2>&1

: Report Output & Log
::  Writes a log about temporary files & folders. 
::  Note: ( %temp% = C:\Users\<user>\AppData\Local\Temp = %userprofile%\AppData\Local\Temp )
::         ( 'WinTemp' = C:\Windows\Temp = %windir%\Temp )
echo: >> %LogPath% 2>&1
echo __________ Empty (0 size) , Old (-1days)  files: >> %LogPath% 2>&1
ForFiles /p "%temp%" /s /d -1 /c "cmd /c if @fsize==0 ECHO @path " >> "%LogPath%" 2>&1
ForFiles /p "%WinTemp%" /s /d -1 /c "cmd /c if @fsize==0 ECHO @path " >> "%LogPath%" 2>&1
echo: >> %LogPath% 2>&1
echo __________ All Old (-1days) files: >> %LogPath% 2>&1
ForFiles /p "%temp%" /s /d -1 /c "cmd /c ECHO @path " >> "%LogPath%" 2>&1
ForFiles /p "%WinTemp%" /s /d -1 /c "cmd /c ECHO @path " >> "%LogPath%" 2>&1
::  Note: "ForFiles"  /p=Path  /s=SubDir  /d=Days(dd)  /c=cmd    "forfiles /?"  for info about command's Variables (@path, @file, etc.)

: Get permissions (unlock files/folders) (OPTIONAL)
::  Uncomment to make it work, IF needed.
::echo: >> %LogPath% 2>&1
::ForFiles /p "%temp%" /s /d -1 /c "cmd /c TAKEOWN /f * /r /d y && ICACLS @file /grant *S-1-3-4:F /t /c /l /q"

: Clean proper files  & Log it
::   Test: ForFiles /p "%temp%\" /s /d -1 /c "cmd /c if @fsize==0 DEL /f /s /q @file" >> "%LogPath%" 2>&1
::        ERROR: Invalid argument/option - '@fsize==0'
echo: >> %LogPath% 2>&1
echo __________ Deleted files: >> %LogPath% 2>&1
forfiles /p %temp%\ /s /d -1 /c "cmd /c DEL /f /s /q @path" >> "%LogPath%" 2>&1
forfiles /p %WinTemp%\ /s /d -1 /c "cmd /c DEL /f /s /q @path" >> "%LogPath%" 2>&1
echo: >> %LogPath% 2>&1
echo __________ Deleted empty directories: >> %LogPath% 2>&1
for /f "delims=" %%d in ('dir %temp%\ /s /b /ad ^| sort /r') do RD "%%d" >> "%LogPath%" 2>&1
for /f "delims=" %%d in ('dir %WinTemp%\ /s /b /ad ^| sort /r') do RD "%%d" >> "%LogPath%" 2>&1
::  Note:  'RD' = Remove-Directory (delete)

: Open Log file
:: this opens the log file    [(my) Documents\Cleaning_LOGs.txt]
explorer.exe %LogPath%

:: https://mcmap.net/q/216463/-how-to-delete-empty-folders-using-windows-command-prompt/46617314#46617314

Note that: The trigger to Experiment with this, as part of a 'pre-process', was to prevent the specific (obsolete) driver of the (also obsolete) sound card from automatically reinstalling at each boot. And clean (ghosted) hidden Devices and more other. (...) (this note was just about to get an idea for the use)

So, in a few words: This is the part that cleans up the 'temp' garbage left behind and gives a report.

Bonaparte answered 13/5, 2022 at 16:50 Comment(0)
E
0

Use for in forfiles:

for /f "delims=" %%d in ('forfiles /s /p %delRoot% /c "cmd /c echo @path" 2^>nul ^| sort /R') do rd %%d 2>nul

sort /R required to delete bottom-up

Ethno answered 17/4, 2024 at 14:23 Comment(0)
S
-1

well, just a quick and dirty suggestion for simple 1-level directory structure without spaces, [edit] and for directories containing only ONE type of files that I found useful (at some point from http://www.pcreview.co.uk/forums/can-check-if-folder-empty-bat-file-t1468868.html):

for /f %a in ('dir /ad/b') do if not exist %a\*.xml echo %a Empty

/ad : shows only directory entries
/b : use bare format (just names)

[edit] using plain asterisk to check for ANY file (%a\* above) won't work, thanks for correction

therefore, deleting would be:

for /f %a in ('dir /ad/b') do if not exist %a\*.xml rmdir %a
Synchronic answered 7/11, 2013 at 15:4 Comment(2)
The test above passes even if the directory is empty.Armoury
@SteveHollasch thanks for comment, I corrected the code aboveSynchronic
E
-4

This can be easily done by using rd command with two parameters:

rd <folder> /Q /S
  • /Q - Quiet mode, do not ask if ok to remove a directory tree with /S

  • /S - Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.

Erhard answered 2/2, 2021 at 13:14 Comment(3)
It deletes all files, not just empty folders.Corvin
Format C: would also remove empty folders and would be a even shorter command ;)Sculpsit
This is a risky answer since it removes all the files in the folder without confirmation. And this is not an answer to the question since the question asks for empty folders only. Be carefulSapsago

© 2022 - 2025 — McMap. All rights reserved.