tags:

views:

351

answers:

2

Hello, i want to search for a program, like this:

cd "C:\"
for /f "delims=" %%f in ('dir /b /s myprogram.exe') do (
)

First problem: i want to let it search trough all hard drives (like 'cd My Computer' or something like that?)

After that, it should make a variable of the directory in which that program is.

How to do that in batch/cmd?

+1  A: 

There is a problem with "cd C:\", it works only when you are on drive C:, but not if you're on another drive. The solution to that is to write the drive's letter first The simpliest way would be to do it this way:

for %%D in (c,d,e,f,g,h,i,j,k,l,m,o) do (
    %%D:
    cd %%D:\
        for /f "delims=" %%f in ('dir /b /s myprogram.exe') do (
        )
)

then it searches for all drives. You could also use

for %%D in (c,d,e,f,g,h,i,j,k,l,m,o) do (
    If exist %%D:\ do (
        %%D:
        cd %%D:\
        for /f "delims=" %%f in ('dir /b /s myprogram.exe') do (
        )
    )
)

Hope it helps.

Camilo Martin
You could try `cd /d %%D:`; the `/d` switch will change to the drive specified, in addition to the directory. Enter `cd /?` from a command line to see if the `/d` switch is supported by your OS.
Patrick Cuff
but, how to make variable of the directory where myprogram is located?
YourComputerHelpZ
In that second for code, %%f will be replaced by the path of "myprogram.exe", such as "D:\folder\myprogram.exe". Since You ask for the folder, using "%~pf" (WITH quotes, since ~ takes them out, and unquoted spaces in paths can mess with the code) would return the folder, not the file (like "E:\Path\To\MyProgFolder" The real issue here is, you can't assign variables normally within a for code. there is a "setlocal enabledelayedexpansion" code for that, but I really don't recommend it, my solution is to either write/read temp files, or redirect as argument to another bat file.
Camilo Martin
+1  A: 

This script will print out the full paths where a file is found:

@echo OFF

for %%D in (c,d,e) do (    
    If exist %%D:\ (        
        for /f "delims=" %%f in ('dir /b /s %%D:\%1 2^> NUL') do (
            @echo %1 found: %%~dpf
        )
    )
)

%%~dpf will have the path to the file for each occurrence found (there may be more than one). If you need to act on these paths you have several options:

  1. Add your file processing commands after the @echo %1 found: %%~dpf line, using %%~dpf as the variable that contains the full path to the file.

  2. Write the path out to a temp text file (@echo %%~dpf >> temp.out), then read that back in another for loop to process.

  3. Concatenate the path to a local environment variable (set FILE_PATHS=!FILE_PATHS!;%%~dpf), then parse that var in another for loop to process.

Patrick Cuff
So for 2nd one i just do that and then later outside the 'for' adding 'set /p=<temp.out' ???
YourComputerHelpZ
For the 2ne one you would need another `for /f` loop operating over the file `temp.out`.
Patrick Cuff