I want to search and delete folders containing a specific string in their names, or delete all files in a folder except one, using a list of paths to browse.
Here's a working example, without the array of paths :
@echo OFF
set "sources0=%userprofile%\New folder with spaces"
set "sources1=%userprofile%\New folder with spaces 2"
set "folder1_to_delete=[test.com]"
set "folder2_name=My folder"
set "file2_to_keep=My app.lnk"
for /D /R "%sources0%" %%d in ("*%folder1_to_delete%*") do (
rem RD /S /Q "%%d" >nul
echo Found1: "%%d"
)
for /D /R "%sources1%" %%d in ("*%folder1_to_delete%*") do (
rem RD /S /Q "%%d" >nul
echo Found1: "%%d"
)
for %%i in ("%sources0%\%folder2_name%\*.*") do if not "%%~ni%%~xi" == "%file2_to_keep%" (
rem DEL /Q "%%i" >nul
echo Found2: "%%i"
)
for %%i in ("%sources1%\%folder2_name%\*.*") do if not "%%~ni%%~xi" == "%file2_to_keep%" (
rem DEL /Q "%%i" >nul
echo Found2: "%%i"
)
pause
exit
Output :
Found1: "C:\Users\marin\New folder with spaces\123 [test.com]"
Found1: "C:\Users\marin\New folder with spaces 2\456 [test.com]"
Found2: "C:\Users\marin\New folder with spaces 2\My folder\New file.txt"
But as I have many search paths, I want to iterate through an array or a list. Here's what I tried, but which doesn't work as expected :
@echo OFF
setlocal enabledelayedexpansion
set "sources[0]=%userprofile%\New folder with spaces"
set "sources[1]=%userprofile%\New folder with spaces 2"
set "folder1_to_delete=[test.com]"
set "folder2_name=My folder"
set "file2_to_keep=My app.lnk"
for /L %%n in (0,1,1) do (
set "source=!sources[%%n]!"
for /D /R "!source!" %%d in ("*%folder1_to_delete%*") do (
rem RD /S /Q "%%d" >nul
echo Found1: "%%d"
)
for %%i in ("!source!\%folder2_name%\*.*") do if not "%%~ni%%~xi" == "%file2_to_keep%" (
rem DEL /Q "%%i" >nul
echo Found2: "%%i"
)
)
pause
exit
Output :
Found2: "C:\Users\marin\New folder with spaces 2\My folder\New file.txt"
Is there a way to achieve what I want, and/or is there a better method to declare and iterate through a list or an array of paths?
Thanks!