0

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!

Deaudouce
  • 167
  • 2
  • 12
  • Put the lists of directories in a file and use the `for /f` style of loop. Batch doesn't do arrays without you having to jump through unnecessary hopes. Keep your data and your code separate. – jwdonahue Oct 22 '18 at 16:51
  • I suggest you to read [Arrays, linked lists and other data structures in cmd.exe batch](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Oct 22 '18 at 19:31
  • Store your filter criteria in a file and use a for /f to process a dir output filtered by a findstr with the /g option. –  Oct 22 '18 at 19:33

0 Answers0