- 1 year ago
Deleting files only in sub-folders using bat script
To delete files only in sub-folders (excluding files in the root folder) using a batch script, you can use the for /r
loop in combination with the if
condition. Here's an example:
batch@echo off
set "rootFolder=C:\Path\to\root\folder"
for /r "%rootFolder%" %%F in (*.*) do (
if not "%%~dpF"=="%rootFolder%\" (
echo Deleting "%%F"
del "%%F"
)
)
Replace C:\Path\to\root\folder
with the actual path to the root folder where you want to delete files. The for /r
loop recursively iterates through all files in the specified root folder and its sub-folders. The if not
condition checks if the file's parent folder is not the root folder, indicating that it is in a sub-folder. The del
command is used to delete the file.
Make sure to test this script on a test folder or make a backup of your files before running it to avoid unintentional file deletion.
Note: The script provided here only deletes files, not directories. If you also want to delete empty sub-folders, you can add an additional loop using the for /d
command to delete empty directories recursively.