Search code examples
batch-filedirectorysubdirectoryfindstr

Exclude certain subfolders when scanning the contents of a folder


I have a batch file that I'm using to scan the c:\ folders (and their respective subfolders) on a Windows 7 box using a for loop. I am having issues in excluding certain folders, such as Users, Windows, LocalAppData etc.

I need to scan through folders in C:\ to find a specific named folder (i.e. "myFolder") without scanning through the above mentioned folders in order to increase the time taken to detect the desired folder within the C: folder.

CODE:

@echo off

for /d /r "c:\" %%a in (*) do (
    findstr /v "Users" "Windows"
)

Solution

  • Use the dir command to return the paths of all wanted directories myFolder, filter them by the findstr command, then capture the result by a for /F loop, like this:

    for /F "delims=" %%D in ('dir /B /S /A:D "C:\myFolder" ^| findstr /I /V /C:"\\Users\\" /C:"\\Windows\\"') do echo/%%D
    

    Of course you can specify more exclusions.


    If you want to have the exceptions located in a text file C:\exclude.txt:

    Users
    Windows
    

    Change the approach like this:

    for /F "delims=" %%D in ('dir /B /S /A:D "C:\myFolder" ^| findstr /I /V /L /G:"C:\exclude.txt"') do echo/%%D