How to delete empty folders using windows command prompt?

WindowsCommand LineCommandDirectory

Windows Problem Overview


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.

Windows Solutions


Solution 1 - Windows

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.

Solution 2 - Windows

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

Solution 3 - Windows

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

Solution 4 - Windows

You don't need usebackq:

FOR /F delims^= %%A IN ('DIR/AD/B/S^|SORT/R') DO RD "%%A"

Solution 5 - Windows

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

Solution 6 - Windows

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.

Solution 7 - Windows

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"`

Solution 8 - Windows

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.

Solution 9 - Windows

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)

Solution 10 - Windows

@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

Solution 11 - Windows

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.

Solution 12 - Windows

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)

Solution 13 - Windows

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.

Solution 14 - Windows

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://stackoverflow.com/questions/7831286/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.

Solution 15 - Windows

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

Solution 16 - Windows

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDEVOPSView Question on Stackoverflow
Solution 1 - WindowsVarun SharmaView Answer on Stackoverflow
Solution 2 - WindowsDinesh RajanView Answer on Stackoverflow
Solution 3 - WindowscorrodedView Answer on Stackoverflow
Solution 4 - Windowstomasz86View Answer on Stackoverflow
Solution 5 - WindowsBozoJoeView Answer on Stackoverflow
Solution 6 - WindowsOglethorpe CadwalladerView Answer on Stackoverflow
Solution 7 - WindowsjcwhallView Answer on Stackoverflow
Solution 8 - Windowssathish anishView Answer on Stackoverflow
Solution 9 - WindowsGreAceView Answer on Stackoverflow
Solution 10 - WindowsPRADEESHView Answer on Stackoverflow
Solution 11 - WindowsCasey PlummerView Answer on Stackoverflow
Solution 12 - WindowsDevadut S BalanView Answer on Stackoverflow
Solution 13 - WindowsRichardView Answer on Stackoverflow
Solution 14 - WindowsAntonyManView Answer on Stackoverflow
Solution 15 - Windowshello_earthView Answer on Stackoverflow
Solution 16 - WindowsHélio Ferreira CabralView Answer on Stackoverflow