Is it possible to create a batch file that searches for a file name, then returns its path so I can use it in a variable?
Asked
Active
Viewed 9.1k times
18

Gilles 'SO- stop being evil'
- 104,111
- 38
- 209
- 254

LabRat
- 1,996
- 11
- 56
- 91
-
Check this to get the solution [Link](http://stackoverflow.com/questions/414715/a-bat-or-wsh-script-that-can-search-for-files) – Murali Dec 14 '12 at 10:37
2 Answers
21
for /r C:\folder %%a in (*) do if "%%~nxa"=="file.txt" set p=%%~dpnxa
if defined p (
echo %p%
) else (
echo File not found
)
If the file you searched for was found it will set the variable %p%
to the full path of the file including name and extension.
If you just want the path (as in the folder path without the file) then use set p=%%~dpa
instead.
Note: If there is more than 1 file with the same name then the variable will be set to the last one found. Also the script after the for
loop line isn't really necessary, just to show you if it found anything :)
If you want to do it using the dir
command then use this, same rules apply
for /f "tokens=*" %%a in ('dir acad.exe /b /s') do set p=%%a

Bali C
- 30,582
- 35
- 123
- 152
-
I was more thinking along the lines of 'find acad.exe /b /s' however I cant get this into a text file or variable... – LabRat Dec 14 '12 at 10:48
-
What do you mean? The `dir` command would have to be run in a `for` loop anyways, why not just run the `for` loop? – Bali C Dec 14 '12 at 10:52
-
I have added another option in my answer to use a `dir` command, more similar to what you wanted :) – Bali C Dec 14 '12 at 11:29
-
1looping through all the files is not good, especially if the folder contains millions of files. Just use `dir /b /s filename` – phuclv Mar 01 '18 at 02:41
5
Do this: -
for /f "delims=" %%F in ('dir /b /s "C:\File.txt" 2^>nul') do set MyVariable=%%F
Assuming you are searching C
drive for File.txt
.

Deb
- 5,163
- 7
- 30
- 45
-
TBH i didn't really understand any of the two answers, but this one looked like it also works with wildcards (i do not know that the other one doesn't!) so it tried it and it worked. – tobi42 May 27 '16 at 07:29
-
This doesn't really do much of a search, you have to know the file and what directory it's in, which isn't what the OP asked for. – OneAdamTwelve Mar 10 '21 at 17:00