views:

172

answers:

2

I came across this piece of batch code. It should find the path to every single .exe file if you enter it.

@Set Which=%~$PATH:1
@if "%Which%"=="" ( echo %1 not found in path ) else ( echo %Which% )

For instance, if you save this code in the file which.bat and then go to its directory in DOS, you can write

which notepad.exe

The result will be: C:\WINDOWS\System32\notepad.exe

But it's a bit limited in that it can't find other executables. I've done a bit of batch, but I don't see how I can edit this code so that it can crawl the hard drive and return the exact path.

+2  A: 

When you want to find an executable (or other file) anywhere on the drive, not just in PATH, then perhaps only the following will work reliably:

dir /s /b \*%!~x1 | findstr "%1"

But still, it's horribly slow. And it doesn't work with cyclic directory structures. And it probably eats children.

You may be much better off using either Windows Search (dependin on OS) or writing a program from scratch which does exactly what you want (the cyclic dir thing might happen on recent Windows versions pretty easily; afaik they have that already by default).

Joey
I'm guessing Object-Oriented languages like Java or C# have built in functions for file locating?
WebDevHobo
They might. I'm not sure. But you can poke around in java.io or System.IO. Maybe you find something but the usual way is "look everywhere and compare with what you search. For Powershell this would look like this: http://subjunctive.wordpress.com/2008/04/01/powershell-file-search/
Joey
A: 

Here's the same thing written in python:


import os

def which(program,additional_dirs=[]):
    path = os.environ["PATH"]
    path_components = path.split(":")
    path_components.extend(additional_dirs)
    for item in path_components:
     location = os.path.join(item,program)
     if os.path.exists(location):
      return location
    return None

If called with just an argument, this will only search the path. If called with two arguments ( the second being an array ), other directories will be searched.Here are some snippets :


# this will search notepad.exe in the PATH variable
print which("notepad.exe")
# this will search whatever.exe in PATH. If not found there,
# it will continue searching in the D:\ drive and in the Program Files
print which("whatever.exe",["D:/","C:/Program Files"])
Geo