- 1 year ago
Batch-file forcing script to remove folder inside subfolders
Comment
1 / 1
To create a batch script that removes a specific folder inside subfolders, you can use the for /r
loop to recursively search for the target folder and then use the rd /s /q
command to remove it. Here's an example batch script that demonstrates this:
batch@echo off
setlocal
rem Set the target folder name to remove
set "targetFolder=FolderToRemove"
rem Set the root directory where the search will start
set "rootDirectory=C:\path\to\root\directory"
rem Loop through subfolders recursively and remove the target folder
for /r "%rootDirectory%" %%D in (.) do (
pushd "%%D"
if exist "%targetFolder%" (
rd /s /q "%targetFolder%"
echo Removed %targetFolder% in "%%D"
)
popd
)
endlocal
Replace FolderToRemove
with the name of the folder you want to remove, and replace C:\path\to\root\directory
with the root directory where the search for subfolders should start.
Here's how the script works:
- The
for /r
loop recursively searches for subfolders starting from the specified root directory. - The loop iterates through each subfolder and navigates into it using
pushd
. - Inside each subfolder, it checks if the target folder exists using
if exist
. - If the target folder exists, it uses the
rd /s /q
command to remove the folder and all its contents. - The script then echoes a message indicating that the target folder was removed.
Please exercise caution when using scripts that delete files or folders. Test the script on non-critical data and make sure you have proper backups before using it in a production environment.