- 1 year ago
(Batch) How to recursively delete all files/folders in a directory except those with a leading .?
Comment
1 / 1
To recursively delete all files and folders in a directory except those with a leading dot (.
) in their names, you can use a batch script with a for
loop. Here's a sample batch script to achieve this:
batch@echo off
setlocal enabledelayedexpansion
set "source_directory=C:\path\to\your\directory"
for /r "%source_directory%" %%F in (*) do (
set "filename=%%~nxF"
if not "!filename:~0,1!" == "." (
if exist "%%F" (
echo Deleting "%%F"
rd /s /q "%%F" 2>nul
del /f "%%F" 2>nul
)
)
)
echo All files and folders (except those with leading dot) have been deleted.
Make sure to replace C:\path\to\your\directory
with the actual path to the directory from which you want to delete the files and folders.
Explanation:
- The
for /r
loop iterates through all files and subdirectories recursively in the specifiedsource_directory
. - The
%%~nxF
retrieves the name and extension of each file in the loop. - The
if not "!filename:~0,1!" == "."
condition checks if the first character of the file name is not a dot (i.e., doesn't have a leading dot). - If the condition is true, the file or folder is deleted using the
rd
(remove directory) anddel
(delete file) commands.
Please be cautious when using this script, as it will delete files and folders permanently without any confirmation. Double-check the source_directory
variable to ensure it points to the correct location. Always take backups before running scripts that delete files or folders to avoid data loss.