To delete empty folders while excluding hidden files
To delete empty folders while excluding hidden files using the command prompt (cmd), you can use a combination of the dir
, for
, and rd
commands in Windows. Here's a step-by-step guide:
Open Command Prompt: Press Win + R
, type cmd
, and hit Enter.
Navigate to the directory where you want to start the deletion process. You can use the cd
command to change directories. For example:
cd "C:\Your\Directory\Path"
Run the following command to delete empty directories while excluding hidden files:
for /f "delims=" %d in ('dir /ad /b /s ^| sort /r') do @(dir /a-d /b "%d" | findstr "." >nul || rd /s /q "%d")
This command will recursively search for all directories (/ad
), list them (/b
for bare format), and sort them in reverse order (/s
for recursive, sort /r
to reverse). Then, for each directory found, it checks if it contains any files (excluding hidden files) using dir /a-d
and findstr "."
. If no non-hidden files are found, it deletes the directory using rd /s /q
.
Remember to replace C:\Your\Directory\Path
with the actual path of the directory you want to clean up. And as always, be cautious when deleting files and folders, as this operation is irreversible. Make sure you have a backup of important data before proceeding.
To delete empty folders while including hidden files
To delete empty folders while including hidden files, you can use a similar approach but modify the command to include hidden files as well. Here's how you can do it:
for /f "delims=" %d in ('dir /ad /b /s ^| sort /r') do @(dir /a /b "%d" | findstr "^" >nul || rd /s /q "%d")
This command will delete empty directories while including hidden files in the check for emptiness. Here's what each part of the command does:
for /f "delims=" %d in ('dir /ad /b /s ^| sort /r') do
: This loop iterates over all directories (/ad
) recursively (/s
) in bare format (/b
) sorted in reverse order (sort /r
).
dir /a /b "%d"
: Lists all files and directories, including hidden ones (/a
), in the specified directory ("%d"
) in bare format (/b
).
findstr "^" >nul
: This command checks if any files or directories are found in the specified directory. If nothing is found, it outputs nothing (redirected to nul
), indicating that the directory is empty.
rd /s /q "%d"
: Deletes the specified directory ("%d"
) recursively (/s
) without prompting (/q
) if it's empty.
Make sure to replace C:\Your\Directory\Path
with the actual path of the directory you want to clean up. As always, exercise caution when deleting files and folders, especially with recursive commands, and ensure you have a backup of important data.
xcopy FROMDIR TODIR /s
. See this SO answer: stackoverflow.com/a/14742810