Skip to content

Instantly share code, notes, and snippets.

@Techlogist
Last active October 3, 2021 12:34
Show Gist options
  • Save Techlogist/5d787722cee45e82ce33b54cc1cafe1a to your computer and use it in GitHub Desktop.
Save Techlogist/5d787722cee45e82ce33b54cc1cafe1a to your computer and use it in GitHub Desktop.
Remove all files and sub-folders in a directory
REM License: GNU General Public License v2.0
REM Author: Miguel
REM Website: www.techlogist.net
REM Post: https://techlogist.net/batch/remove-all-files-and-sub-folders-in-a-directory/
REM Description: Remove all files and sub-folders in a directory
REM OS/Language/Region: Windows/EN-US
@echo off
title Delete files and folders in a folder
color f0
mode con:cols=70 lines=10
goto start
:start
REM Define the file path
cls
echo.
set _file_path=
set /p _file_path=Please enter the file path:
goto _check_dir
:_check_dir
REM Confirm that the directory exists
cls
if exist "%_file_path%" (goto _confirm_files) else (goto _error_path)
:_confirm_files
REM Confirm the folder is empty
set _file_count=
for /f "delims=" %%a in ('dir /b "%_file_path%"') do set _file_count="%%a"
if [%_file_count%]==[] (goto _error_file) else (goto _confirm_del)
:_error_path
REM Error message
cls
echo.
echo The file path is not valid!
echo.
echo Press any key to continue...
pause>nul
goto start
:_error_file
REM Error message
cls
echo.
echo The file path is empty!
echo.
echo Press any key to continue...
pause>nul
start explorer.exe %_file_path%
goto start
:_confirm_del
REM Confirm deletion
echo.
set /p _confirm_del=To continue press Y (Yes) or N (No) to set the path again.
if /i "%_confirm_del%"=="y" (goto _delete) else (goto _error_input)
if /i "%_confirm_del%"=="n" (goto _restart) else (goto _error_input)
:_error_input
cls
echo.
echo Your choice is invalid!
echo.
echo Press any key to continue...
pause>nul
goto _confirm_del
:_error_input_2
cls
echo.
echo Your choice is invalid!
echo.
echo Press any key to continue...
pause>nul
goto _restart
:_restart
echo.
set /p _confirm_restart=To set the path again press Y (Yes) or N (No) to exit.
if /i "%_confirm_restart%"=="y" (goto start) else (goto _error_input_2)
if /i "%_confirm_restart%"=="n" (goto exit) else (goto _error_input_2)
:_delete
REM Delete the files
cls
echo.
echo Deleting...
forfiles /P "%_file_path%" /M * /C "cmd /c if @isdir==FALSE del @file"
forfiles /P "%_file_path%" /M * /C "cmd /c if @isdir==TRUE rmdir /S /Q @file"
goto deleted
:_deleted
cls
echo.
echo The files were deleted sucessfully.
pause>nul
goto exit
:exit
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment