How do I get a relative path out of a windows batch file using echo? - windows

How do I get relative directories / partial paths to display as echo output from a windows .bat file?
How to split the filename from a full path in batch?
Talks about everything but.
I've found drive letters, filenames, extensions, shortened (8.3) names, and full paths - but no relative paths.
I'm running a recursive FOR /R loop; which traverses sub-directories. I would like something - that doesn't have twenty characters of useless path info - that tells me which directory each duplicate file lives in... without hardcoding the .bat file to live in a certain directory/path?
Maybe a solution would be to measure the length of the script's path and cut that off of the front of the full path? But I don't know how to manipulate that.
Script could be in many locations:
F:\a.bat<BR>
F:\Dir1\fileA.txt<BR>
F:\Dir20\fileA.txt
C:\Users\Longusername\Desktop\Container\a.bat<BR>
C:\Users\Longusername\Desktop\Container\Dir1\fileA<BR>
C:\Users\Longusername\Desktop\Container\Dir20\fileA
And right now the only options I have for output are (%%~nxG):
fileA.txt
fileA.txt
Which doesn't tell me which directory each file is in...or (%%~pnxG)
\Users\Longusername\Desktop\Container\Dir1\fileA.txt
\Users\Longusername\Desktop\Container\Dir20\fileA.txt
What I'd like, from any location:
\Dir1\fileA.txt
\Dir20\fileA.txt
Could be missing the leading \, but that's negligible. Other options than echo are permissible if they'll work on most window machines. They may lead to more questions, though - as I've figured out my other pieces with echo.

quite easy, if you think about it: just remove the current directory path (%cd%):
#echo off
setlocal enabledelayedexpansion
for /r %%a in (*.txt) do (
set "x=%%a"
echo with \: !x:%cd%\=\!
echo without \: !x:%cd%\=!
)
By the way: \folder\file always refers to the root of the drive (x:\folder\file), so it's not exactly a relative path.

This is similar to the already accepted answer, but with delayed expansion enabled only where needed. This should correctly output filenames containing ! characters.
#Echo Off
SetLocal DisableDelayedExpansion
Set "TopLevel=C:\Users\LongUserName"
For /R "%TopLevel%" %%A In ("*.txt") Do (
Set "_=%%A"
SetLocal EnableDelayedExpansion
Echo=!_:*%TopLevel%=!
EndLocal
)
Pause
You could also use Set "TopLevel=%~dp0", (the running script's directory) or Set "TopLevel=%~dp0..", (the running script's parent directory)
One potential benefit of the above method is that you can also use a location relative to the current directory for the value of %TopLevel% too, (in this case, based upon the initial example, the current directory would be C:\Users):
Set "TopLevel=LongUserName"
Although this would only work correctly if LongUserName didn't already exist as content of the path earlier in the tree.

You could use xcopy together with its /S (include sub-directories) and /L (list but do not copy) options since it returns relative paths then, so you do not have to do any string manipulation, which might sometimes be a bit dangerous, particularly when the current directory is the root of a drive:
xcopy /L /S /I /Y /R ".\*.txt" "\" | find ".\"
The appended find command constitutes a filter that removes the summary line # File(s) from the output.
To capture the output of the aforementioned command line just use a for /F loop:
for /F "delims=" %%I in ('
xcopy /L /S /I /Y /R ".\*.txt" "\" ^| find ".\"
') do (
rem // Do something with each item:
echo/%%I
)

Related

Batch File Variable to copy specific files

I'm trying to copy specific files from C: to "X: for example". The files are named with the same format.
A1234_ZZabc123_DT1_F1.tst
A4567_ZZdef4567_DT2_F2.tst
A8901_ZZghi1289_DT1.tst
A2345_ZZjfkbu12_to_modify.tst
A6789_ZZlmny568_F1_to_modify.tst
A1234_ZZabc478_DT1.txt
I want to copy only the .tst files, and with the same format as the first 3 Axxxx_ZZyyyxxx_DTx_Fx.tst where x=number and y=letter.
After ZZ, it might be 4 letters and 3 numbers, or 5 letters and 4 numbers, like a "namecode".
Example: ZZkusha122 or ZZkus1551.
I need to copy the folders along with the files too.
I'm new to coding and really need some help.
I need to find and copy all those files along 10k+ files together
You claim that the first 3 of your example filenames fit the pattern you describe. I believe that only two do.
#ECHO OFF
SETLOCAL
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
FOR /f "delims=" %%e IN (
'dir /b /a-d "%sourcedir%\A*.tst"^|findstr /X /I /R "A[0-9][0-9][0-9][0-9]_ZZ[a-z][a-z][a-z]_DT[0-9]_F[0-9].tst" '
) DO ECHO COPY "%sourcedir%\%%e" X:
)
GOTO :EOF
Always verify against a test directory before applying to real data.
The required COPY commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO COPY to COPY to actually copy the files. Append >nul to suppress report messages (eg. 1 file copied)
Simply execute a dir command that reports only filenames matching the *.tst mask. Filter this list with findstr which /X exactly matches the regular expression provided. findstr only has a limited implementation of regular expressions. The /I forces a case-insensitive match. If you want case-sensitive, remove the /I and change each [a-z] to [a-zA-Z] (leave as-is if you want lower-case only in these positions.)
See findstr /? from the prompt for more documentation, or search for examples on SO.
---- revision to cater for multiple filemasks and subdirectories ---
#ECHO OFF
SETLOCAL
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "maskfile=%sourcedir%\q74442552.txt"
FOR /f "tokens=1*delims=" %%e IN (
'dir /b/s /a-d "%sourcedir%\*.tst"^|findstr /E /I /R /g:"%maskfile%" '
) DO ECHO COPY "%%e" X:
)
GOTO :EOF
Changes:
Establish a file, name irrelevant, as maskfile
The dir command requires the /s switch to scan subdirectories
The filemask for the dir command loses the initial A
The findstr command replaces the /X switch with /E
The findstr command loses the regex expression. These are transferred to a file and the file is nominated by the /g: switch.
The copy command loses the source-directory as the directory will be included in %%e
The file "q74442552.txt" contains lines that are of the form
A[0-9][0-9][0-9][0-9]_ZZ[a-z][a-z][a-z]_DT[0-9]_F[0-9].tst
A[0-9][0-9][0-9][0-9]_ZZ[a-z][a-z][a-z]_to.*.tst
This time, %%e acquires the full pathname of the files found. Since the filemask ends .tst, the only filenames to pass the dir filter will be those that end .tst.
The /e switch tells findstr to match string that End with the regex strings in the file specified as /g:.
The strings in the file must comply with Microsoft's partial regex implementation, one to a line.
In summary, findstr uses as regex
Any character,literally
[set] any character of a set of characters
[^set] any character not in a set of characters
. any character
.* any number of any character
prefix any of the special characters with\ to use it literally
a set may include a range by using low-high
So - you then need to brew-your own using the examples I've supplied. The second line matches Axxxx_ZZyyy_to{anything}.tst for instance.
--- Minor revision to deal with maintaining destination-tree -----
(see notes to final revision for why this doesn't quite work)
#ECHO OFF
SETLOCAL
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "maskfile=%sourcedir%\q74442552.txt"
SET "destdir=u:\your results"
FOR /f "tokens=1*delims=" %%e IN (
'dir /b/s /a-d "%sourcedir%\*.tst"^|findstr /E /I /R /g:"%maskfile%" '
) DO ECHO "%%~nxe"&XCOPY /Y /D /S "%sourcedir%\%%~nxe" "%destdir%\">nul
)
GOTO :EOF
This version adds the destination root directory as destdir.
The dir ... findstr... works as before to list the filenames to copy.
The prior version used echo copy to report the proposed copy operation, but the destination was always the same directory.
The replacement XCOPY line maintains the directory structure at the destination.
Note : the XCOPY is "live". The files will be copied to the destination if run as-is. Always verify against a test directory before applying to real data.
To "defuse" the XCOPY, add the /L switch and remove the >nul. This will cause XCOPY to report the source name that would be copied instead of copying it. (The >nul suppresses the report)
The /D only copies source files that eitherr do not exist in the destination of have a later datestamp in the source.
The action is to xcopy each filename found (%%~nxe) from the source directory tree to the destination. Therefore, any file xyz.tst found anywhere in the source tree will be xcopyd to the destination tree. The /D means that once xyz.tst is encountered on the source tree, it will be skipped should it be encountered again.
--- Final (I hope) revision ---
#ECHO OFF
SETLOCAL
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=U:\Users\tocil\Desktop\aoi"
SET "maskfile=%sourcedir%\q74442552.txt"
SET "destdir=u:\your results"
FOR /f "tokens=1*delims=" %%e IN (
'dir /b/s /a-d "%sourcedir%\*.tst"^|findstr /E /I /R /g:"%maskfile%" '
) DO (
rem drive and path to 'dirname' - has terminal "\"
SET "dirname=%%~dpe"
rem remove the sourcedir from dirname
FOR %%y IN ("%sourcedir%") DO CALL SET "dirname=%%dirname:%%~y=%%"
rem copy or xcopy the file to the destination.
FOR /f "tokens=2delims==" %%y IN ('set dirname') DO XCOPY /Y "%%e" "%destdir%%%y">nul
)
)
GOTO :EOF
Always verify against a test directory before applying to real data.
Note to self: Only if the filemask provided to XCOPY is ambiguous (ie. contains ? or *) will XCOPY obey the /s switch unless the target file exists in the starting source directory.
hence
xcopy /s sourcedir\myfile destdir
will copy myfile from the entire tree ONLY if sourcedir\myfile exists.
xcopy /s sourcedir\myf?le destdir
will copy myfile from the entire tree regardless. Unfortunately it will also copy myfale and myfule as well.
Hence, the new approach.
First, perform a dir /b /s to get all of the filenames and filter as before. This is being assigned to %%e.
Take the drive and path only of the file and assign to dirname.
The next step is a little complex. First, set the value of %%y to the name of the source directory. Next, use a parser trick to remove that name from dirname. The mechanics are: Parse the %%dirname:%%~y=%% (because the call causes the set to be executed in a sub-shell) whuch does the normal left-to-right evaluation. %% is an escaped-%, so is replaced by %; %%y is an active metavariable so is replaced by (the name of the source directory) and the ~ causes the quotes to be stripped from that name. The resultant command executed is thus SET "dirname=%dirname:nameofsourcedirectory=%"
So now we can construct a copy-class instruction. dirname now contains the relative directory for the destination, which we can extract from the environment by parsing a set listing (Could also be done with delayed expansion) where %%y gets set to the relative directory and has both a leading and trailing backslash, so the destination directory is simply "%destdir%%%y". XCOPY then knows to create that directory if necessary (%%y has a trailing backslash) and we know the source filename is in %%e.
You could also use a copy to do the same thing, but you'd need to create the destination directory first. Another advantage of XCOPY is that you can also specify the /d switch to not copy files that have an earlier date over files that have a later date.

Batch file that searches for a folder with the same name as a local file and moves said file to the located folder not working

So I am trying to create a batch file that will take a pdf file in the same directory as the batch file and output the file name (sans extension). I used this code to accomplish this:
#echo off
for /r "C:\Users\me\Test Folder" %%G in (*.pdf) do set "name=%%~nG"
This works fine. The next step is to search another directory and find a directory within the searched directory whose name matches the output of the above code (stored in the %name% variable). Here's what I tried:
dir "P:\Accounting\Acc Pay" | find %name% | set "loc=%%~dp"
The goal of the above code was to find only the directories that had the same name as the original pdf file and then set the drive and path of the output to a variable %loc%. I think this is where I messed up.
Once the path to the folder is set to %loc%, I then am supposed to finish with this line:
move .\*.pdf %loc%
This would take all the pdf files (there will only be one in the directory at once) in the directory with the batch file and move it to the path currently stored in the %loc% variable.
In total the code looks like this:
#echo off
for /r "C:\Users\me\Test Folder" %%G in (*.pdf) do set "name=%%~nG"
for /r %%A in ('dir "P:\Accounting\Acc Pay" | find %name%') do set "loc=%%~dpA"
move .\*.pdf %loc%
However, the code seems to move the pdf file into the same location it was already in (ie the folder with the batch file). I assume the %loc% variable is not working properly. Any help much appreciated.
Like #Magoo said (^|). And you surely want to add the following switches for the dir command: /b for "bare format" (name only) and /ad for "Attribute Directory" to return folder names only. find needs its's argument quoted, and for safety, the destination for the move command should also be quoted. Your find could benefit from /i to make it case-insensitive.
I personally would do it with nested loops to avoid creating superflouos variables:
#echo off
for /r "C:\Users\me\Test Folder" %%G in (*.pdf) do (
for /r %%A in ('dir /b /ad "P:\Accounting\Acc Pay" ^| find /i "%%~nG"') do (
move "%%G" "%%~dpA"
)
)
Bonus: should there be more than one .pdf file (maybe after the Weekend or Holidays), this would process all of them correctly in one go.
Depending on your naming structures, consider replacing find /i "%%~nG" with findstr /iblc:"%%~nG" (see findstr /?to find out what the switches mean)
(Note to prevent confusion: findstr is the only command (as far as I'm aware) that supports concatenating switches into one. /iblc is the same as /i /b /l /c)

remove the directory from output in batchfile

I have the below batchfile that output ReadFile.txt file
cd /d "T:\EMP\SST"
for /r %%i in (T:\EMP\SST) do echo %%i >>D:\MultiThreading\ReadFile.txt
pause
this ReadFile.txt file output
T:\EMP\SST\T:\EMP\SST
T:\EMP\SST\file 11\T:\EMP\SST
T:\EMP\SST\file 12\T:\EMP\SST
T:\EMP\SST\file 13\T:\EMP\SST
I want to remove the directory ouptput T:\EMP\SST so I want my output to be like this
file 11
file 12
file 13
how to do this
I believe you actually need for /D rather than for /R for your task (because I assume file 11, file 12, file 13 are actually directories as they are enumerated by for /R):
for /D %%I in (T:\EMP\SST\*) do echo %%~nxI
Anyway, your for /R syntax is wrong; the directory you want to enumerate recursively needs to be stated immediately after the /R switch (if you omit it, the current directory is assumed), and you need to provide a set (that is the part in between parentheses) that constitutes a pure file name pattern only, without any (absolute or relative) paths, like *.*, for example, to match all files.
In your code, for /R enumerates the current directory. Since your set is T:\EMP\SST and contains no wildcards (*, ?), it is just appended to the enumerated directories literally, because for accesses the file system only in case wildcards are encountered. That explains your weird output.
you're using FOR in a wrong way. The pattern between the parentheses isn't the start directory, it is the file/directory pattern you want to match. Here I suppose you want *.*
If you only want the filenames (no paths at all) you can write:
#echo off
for /r T:\EMP\SST %%i in (*.*) do echo %%~nxi>>D:\MultiThreading\ReadFile.txt
If you want the filenames + relative paths, it's slightly more complicated but doable, by enabling delayed expansion to be able to remove the path prefix + backslash:
#echo off
setlocal enabledelayedexpansion
set start_path=T:\EMP\SST
for /r %start_path% %%i in (*.*) do (
set f=%%i
echo !f:%start_path%\=!>>D:\MultiThreading\ReadFile.txt
)
This FOR command is cryptic and I have to read the help (FOR /?) everytime, but the fact is: everything useful is in there so I do it all the time :)

For loop in batch file reading a file of File Paths

I want to write a Windows batch file script that will loop through a text file of FILE PATHS, do some work using data from each file path, then ultimately delete the file.
I started by running the FORFILES command and sending its output (the #PATH parameter is the full path of any file it matches) to a text file (results.txt).
I end up with a results.txt file like this:
"C:/Windows/Dir1/fileA.log"
"C:/Windows/Dir1/fileA.log"
"C:/Windows/Dir2/fileC.log"
"C:/Windows/Dir3/fileB.log"
What I want to do is:
Use a FOR loop and read each line in the results.txt file
For each line (file path), strip out the directory name that the log file is sitting in (ie: Dir1, Dir2, etc..) and create a directory with that SAME name in a different location (ie. D:/Archive/Backups/Dir1, D:/Archive/Backups/Dir2, etc..) -- assuming the directory doesn't exist.
Move the actual .log file to a zip file in that directory [I have code to do this].
Delete the .log file from its original location. [Pretty straightforward]
I'm having trouble figuring out the best way to accomplish the first 2 steps. My FOR loop seems to stop after reading the very first line:
FOR /F "tokens=1,2,3,4,5,6,7,8,9,10 delims=\" %%G in ("results.txt") DO (
...
)
You don't want to parse the path with the tokens/delims options because you don't know how many directory levels you are dealing with. You want to preserve each line in its entirety. TO parse the path you want to use the FOR variable modifiers. (type HELP FOR from the command line and look at the last section of the output)
%%~pG gives the path (without the drive or file name). If we then strip off the last \, we can go through another FOR iteration and get the name (and possible extension) of the file's directory by using %%~nxA.
The toggling of delayed expansion is just to protect against a possible ! in the path. If you know that no path contains ! then you can simply enable delayed expansion at the top of the script and be done with it.
EDIT - this code has been modified significantly since Aacini pointed out that I misread the requirements. It should satisfy the requirements now.
for /f "usebackq delims=" %%G in ("results.txt") do (
set "myPath=%~pG"
setlocal enableDelayedExpansion
for /f "eol=: delims=" %%A in ("!myPath:~0,-1!") do (
endlocal
if not exist d:\Archive\Backups\%%~nxA md d:\Archive\Backups\%%~nxA
rem ::zip %%G into zip file in the D: location
rem ::you should be able to create the zip with the move option
rem ::so you don't have to del the file
)
)
I wrote this to timestamp files before offloading to SFTP.
Hope you find it useful.
The timestamp coding may seem irrelevant to your issue, but I left it because it's a good example of dissecting the filename itself.
I suggest you put an ECHO in front of the REN command for testing. Different shells may have different results.
In the end, the delayedexpansion command wasn't necessary. It was the sub-routine that fixed my issues with variables inside the loop. That could possibly be because of my OS ver. (Win 8.1) - It wouldn't hurt to leave it.
#echo off
cls
setlocal enabledelayedexpansion
if %time:~0,2% geq 10 set TIMESTAMP=%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if %time:~0,2% leq 9 set TIMESTAMP=%date:~10,4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
echo TimeStamp=%TIMESTAMP%
echo.
for %%G in (*.txt) do (
set OLDNAME=%%G
call :MXYZPTLK
)
dir *.txt
goto :EOF
:MXYZPTLK
echo OldName=%OLDNAME%
ren %OLDNAME% %OLDNAME:~0,-4%_%TIMESTAMP%%OLDNAME:~-4,4%
echo.
:END
You have two minor problems:
The path separator in the file is '/' but you use '\' in the for loop.
The quotes around "results.txt" stop it working.
This works. Don't write quotes to results.txt and you won't get a quote at the end of the filename.
#echo off
FOR /F "tokens=3,4 delims=/" %%I in (results.txt) DO (
REM Directory
echo %%I
REM File
echo %%J
)

How do I find full path to an application in a batch script

How do I in a batch script find the full path to application XYZ if it is installed
Clarifications:
The application is not in the PATH
All I have is it's name in this case "ISTool.exe" and I would like to get C:\Program\ISTool\ISTool.exe
You can locate an executable on the path (or other path-like string if necessary):
c:\> for %i in (cmd.exe) do #echo. %~$PATH:i
C:\WINDOWS\system32\cmd.exe
c:\> for %i in (python.exe) do #echo. %~$PATH:i
C:\Python25\python.exe
Details can be found at the end of the help text for the "for" command, "for /?" but the summary is:
%~i - expands %i removing any surrounding quotes.
%~fi - expands %i to a fully qualified path name.
%~di - expands %i to a drive letter only.
%~pi - expands %i to a path only.
%~ni - expands %i to a file name only.
%~xi - expands %i to a file extension only.
%~si - expanded path contains short names only.
%~ai - expands %i to file attributes of file.
%~ti - expands %i to date/time of file.
%~zi - expands %i to size of file.
%~$P:i - searches the directories listed in the P environment variable
and expands %i to the fully qualified name of the first one found.
If the environment variable name is not defined or the file is not
found by the search, then this modifier expands to the empty string.
The modifiers can be combined to get compound results:
%~dpi - expands %i to a drive letter and path only.
%~nxi - expands %i to a file name and extension only.
%~fsi - expands %i to a full path name with short names only.
%~dp$P:i - searches the directories listed in the P environment variable
for %i and expands to the drive letter and path of the first
one found.
%~ftzai - expands %i to a DIR like output line.
If your executable isn't on the path (as per your edit), your best bet is to use the bare/subdirectory format of dir which will do it for you. From the root directory:
dir /b /s ISTool.exe
will get you all of the files on that drive with that name. You then just have to parse the output. My own preference would be to use Cygwin's "find /cygdrive -name ISTool.exe" but that's because I already have it installed. You may not want that (or even have that option).
Update:
That dir /b /s command will take a while since it's basically searching the whole disk. If that's a problem you may want to consider periodically creating a cached record of all files on all disks with a cmd file like:
#echo off
setlocal enableextensions enabledelayedexpansion
del c:\files.cache.tmp >nul: 2>nul:
for %%d in (c d e) do (
cd /d %%d:\
dir /b /s >>c:\files.cache.tmp
)
del c:\files.cache >nul: 2>nul:
move c:\files.cache.tmp c:\files.cache
endlocal
You could do this with scheduled tasks either nightly (for an always-on server) or on boot (for a desktop). You could even make the script more intelligent to do it only every couple of days (I have an automated backup script that does a similar thing on the family machines I support). This creates the list in a temporary cache file then overwrites the original one to ensure the time when the file doesn't exist is minimized.
Then you can just use:
findstr \\ISTool.exe c:\files.cache
to locate all your files.
Based on the really helpful answers here I hacked up these two batches which I thought I share here (I know this thread is now 3 years old, but its found as 1st match when googling ...):
1) which.bat:
#echo off
REM emulate the Linux which command
if "%1" == "" (
echo Usage: %~nx0 ^<command[.ext]^>
exit /b
)
setlocal
for %%P in (%PATHEXT%) do (
for %%I in (%1 %1%%P) do (
if exist "%%~$PATH:I" (
echo %%~$PATH:I
exit /b
)
)
)
not perfect because there are allways two tests, but its fast enough so I didnt further bother about; sure its possible to 1st do a separate test with %1 only ...
2) findfile.bat:
#echo off
REM emulate the Linux find command
if "%1" == "" (
echo Usage: %~nx0 ^<startdir^> ^<file^>
exit /b
)
setlocal
for /f "delims=" %%A in ('dir /b /s %1\%2') do set F=%%A
if exist "%F%" echo %F%
This is the closest I got. One drawback is that it works only for one drive per execution, but that could made more flexible. Another is the output, that always contains a // between the path and the filename. But per definition thats a valid path.
#ECHO OFF
SET filename=autoexec.bat
FOR /R C:\ %%a IN (\) DO (
IF EXIST "%%a\%filename%" (
SET fullpath=%%a%filename%
GOTO break
)
)
:break
ECHO %fullpath%
Will deliver: C:\\autoexec.bat
EDIT:
For explanation, the for loop iterates through all directories starting at the given path (C:\) and check if the filename exists in that directory. If so, both variables are concatenated and stored in %fullpath% and the loop is terminated by a jump.
Sometimes this simple solution works, where you check to see if the output matches what you expect. The first line runs the command and grabs the last line of standard output.
FOR /F "tokens=*" %%i in (' "xcopy /? 2> nul" ') do SET xcopyoutput=%%i
if "%xcopyoutput%"=="" echo xcopy not in path.
Alternately, programs like Everything, and UltraSearch (freeware), SwiftSearch can search the MFT (of your NTFS partition) for files (so it can do so very quickly), (but Wikipedia claims this kind of thing can breach your security model by finding things it's not supposed to) -- some of them look like they have some command line parameters, I've not used them, but maybe it could be helpful, if you're resorting to a full drive search.
The answers I got from others worked (but slow or used extra files) and worked for any exe but didn't really suit my needs.
Since I wanted to find a particular exe I went looking in the registry using REG QUERY instead. I found a key that contained the data I wanted to find and extracted that.
The result is fast, has few lines of code but is not very pretty nor reusable.
Short example:
#ECHO off
SETLOCAL
set found=
FOR /F "tokens=1-3 delims= " %%a IN ('REG QUERY "HKEY_CLASSES_ROOT\Applications\ISTool.exe\shell\OpenWithISTool\command"') DO (
set found=%%c
)
for /f "tokens=1-2" %%a in ("%found%") do (
set my_exe=%%a
)
echo %my_exe%
ENDLOCAL
This results in "C:\Program\ISTool\ISTool.exe" (with quotes)
Note: delims= above is followed by a tab-char

Resources