Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For /d /r loop not traversing sub-directories for finding desired directory recursively in Batch/CMD script

As aforementioned in Question title, I have a Batch/CMD(OS: Windows 10 64Bit) script to traverse the subfolders inside %LocalAppData% if the passed argument to script is Chrome, and recursively find and list out all folders containing word Cache at any position.

The script I have come up with relying on for /d /r loop is this:

@echo off && setlocal EnableDelayedExpansion
if /i "%1" equ "chrome" (
    set "subPath0=\Google"
    set "subPath1=\User Data"
    for /d /r "%LocalAppData%!subPath0!\%1" %%i in (*Cache*) do (
        echo "%%i"
    )
) else (
    for /d /r "%Appdata%\%1" %%i in (*Cache*) do (
        echo "%%i"
    )
)

But regardless of I escape the closing brackets inside for loop like (*Cache*^) or not, the above loop is not listing out any *Cache* directories recursively, even though there are actually Cache folders inside the path(the one on which for loop is running) inside User Data folder.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So can anyone point out what am I doing wrong here and help fix this ?

Note: I know Powershell is good option to Batch/CMD, but this is supposedly part of larger script, so appreciate it much if suggestions/fixes in Batch/CMD.

>Solution :

Remove the path from the FOR command and use a PUSHD instead.

@echo on
setlocal EnableDelayedExpansion
if /i "%1" equ "chrome" (
    set "subPath0=\Google"
    set "subPath1=\User Data"
    pushd "%LocalAppData%!subPath0!\%~1"
    for /D /R %%i in (*Cache*) do (
        echo "%%i"
    )
    popd
) else (
    pushd "%Appdata%\%1"
    for /d /r %%i in (*Cache*) do (
        echo "%%i"
    )
    popd
)

Why not simplify it to one FOR command?

@echo on
setlocal EnableDelayedExpansion
if /i "%~1" equ "chrome" (
    set "subPath0=\Google"
    set "subPath1=\User Data"
    set "searchpath=%LocalAppData%!subPath0!\%1"

) else (
    set "searchpath=%Appdata%\%~1"
)

for /d /r "%searchpath%" %%i in (*Cache*) do echo "%%i"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading