Find file and return full path using a batch file

79,460

Solution 1

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

Solution 2

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 .

Share:
79,460
LabRat
Author by

LabRat

Updated on July 29, 2020

Comments

  • LabRat
    LabRat almost 4 years

    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?

  • LabRat
    LabRat over 11 years
    I was more thinking along the lines of 'find acad.exe /b /s' however I cant get this into a text file or variable...
  • Bali C
    Bali C over 11 years
    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
    Bali C over 11 years
    I have added another option in my answer to use a dir command, more similar to what you wanted :)
  • tobi42
    tobi42 almost 8 years
    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.
  • phuclv
    phuclv about 6 years
    looping through all the files is not good, especially if the folder contains millions of files. Just use dir /b /s filename
  • OneAdamTwelve
    OneAdamTwelve about 3 years
    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.