Friday, May 29, 2015

Removing the empty directories from Windows command line


To delete the empty directories from the MS windows use the following command.


Use this command  (RD in the command deletes only empty directories so ypou dont loose any files here

FOR /F delims^= %A IN ('DIR/AD/B/S^|SORT/R') DO RD "%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



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

No comments: