Windows – How to exclude specific directories from a Windows search

batch filewindowswindows-search

I want to search for a file on drive C:. I know for sure it does not exist in a specific directory(s) (say Program Files). So to shorten my search time, I want Windows to exclude searching in those specific folders. How can I perform such a search (which searches in the C drive but can skip specific folders)?

I would prefer the answer to be a method for Windows search, but am not opposed to it being a script or other simple program.

Best Answer

In line with user117893's answer and using the dir command in a for loop. You can use robocopy or xcopy with the /L (list only) option to search for files.

Robocopy

Just specify the starting directory C:\ and the target file name *File.txt

robocopy C:\ %Temp% *File.txt /S /XD Windows "Program Files" "Program Files (x86)" /XJ /L /NS /NC /NDL /NP /NJH /NJS

Output

C:\Users\Username\Desktop>robocopy C:\ %Temp% *Snapshot.txt /S /XD Windows "Program Files" "Program Files (x86)" /XJ /L /NS /NC /NDL /NP /NJH /NJS

                            C:\Temp\2013-02-13-1408-31_Snapshot.txt
                            C:\Temp\2013-02-13-1523-47_Snapshot.txt
                            C:\Temp\2013-02-13-1534-17_Snapshot.txt
                            C:\Temp\2013-02-13-1535-55_Snapshot.txt
                            C:\Temp\2013-02-13-1537-44_Snapshot.txt
                            C:\Temp\2013-02-18-1552-44_Snapshot.txt
                            C:\Temp\2013-02-18-1553-21_Snapshot.txt
                            C:\Temp\2013-02-18-1556-05_Snapshot.txt
                            C:\Temp\2013-02-18-1558-45_Snapshot.txt
                            C:\Temp\2013-02-18-1610-06_Snapshot.txt

xcopy

setup takes a couple extra steps.

  1. An exclude.txt text file must be created which contains the keywords to exclude in the search.
  2. To prevent a cyclical copy error message, a temporary drive letter must be created or another drive must be used as the target directory.
  3. Then specify the starting directory C:\ and the target file name *File.txt

exclude.txt

\Windows\
\Program Files\
\Program Files (x86)\

Commands

subst Z: %Temp%
xcopy C:\*File.txt Z:\ /S /L /EXCLUDE:exclude.txt
subst Z: \d

Output

C:\Users\Username\Desktop>xcopy C:\*Snapshot.txt Z:\ /S /L /EXCLUDE:exclude.txt
C:\Temp\2013-02-13-1408-31_Snapshot.txt
C:\Temp\2013-02-13-1523-47_Snapshot.txt
C:\Temp\2013-02-13-1534-17_Snapshot.txt
C:\Temp\2013-02-13-1535-55_Snapshot.txt
C:\Temp\2013-02-13-1537-44_Snapshot.txt
C:\Temp\2013-02-18-1552-44_Snapshot.txt
C:\Temp\2013-02-18-1553-21_Snapshot.txt
C:\Temp\2013-02-18-1556-05_Snapshot.txt
C:\Temp\2013-02-18-1558-45_Snapshot.txt
C:\Temp\2013-02-18-1610-06_Snapshot.txt
10 File(s)

Notes

The target is needed only to use the commands (%Temp%), nothing is actually copied due to /L

Both command took under a couple seconds to run with the listed exclusions.

Related Question