搜索一系列路径以删除包含字符串的文件夹-批处理

时间:2018-10-22 16:24:37

标签: arrays string list batch-file

我想使用浏览路径列表搜索和删除名称中包含特定字符串的文件夹,或者删除除一个文件夹以外的所有文件。

这是一个有效的示例,没有路径数组:

@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

输出:

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"

但是由于我有许多搜索路径,所以我想遍历数组或列表。这是我尝试过的方法,但未按预期工作:

@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

输出:

Found2: "C:\Users\marin\New folder with spaces 2\My folder\New file.txt"

有没有一种方法可以实现我想要的,和/或有没有更好的方法来声明和遍历列表或路径数组?

谢谢!

0 个答案:

没有答案
相关问题