views:

4161

answers:

12

I would like to find the full path to a program in Windows. Is there an equivalent to the UNIX command 'which'? On UNIX, which command prints the full path of the given command.

+5  A: 

There isn't one built in, but you can use a Python script: wh.py

Ned Batchelder
+6  A: 

Not in stock Windows but it is provided by Services for Unix and there are several simple batch scripts floating around that accomplish the same thing such this this one.

Robert Gamble
+2  A: 

The best version of this I've found on Windows is Joseph Newcomer's "whereis" utility, which is available (with source) from his site.

The article about the development of "whereis" is worth reading.

Tim Lesher
+2  A: 

If you have PowerShell installed (which I recommend), you can use the following command as a rough equivalent (substitue programName for your executable's name):

($Env:Path).Split(";") | Get-ChildItem -filter programName*

More here: http://www.codeassassin.com/blog/PermaLink,guid,fd1967d1-f844-4e29-82e2-f2d6424b4ef9.aspx

RexE
Why the downmod?
RexE
+29  A: 

You can do this with standard Windows by using the environment variable modifiers, as follows:

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

You don't need any extra tools and it's not limited to PATH since you can substitute any environment variable (in the path format, of course) that you wish to use.


And, if you want one that can handle all the extensions in PATHEXT (as Windows itself does), this one does the trick:

@echo off
setlocal enableextensions enabledelayedexpansion

:: Needs an argument.

if "x%1"=="x" (
    echo Usage: which ^<progName^>
    goto :end
)

:: First try the unadorned filenmame.

set fullspec=
call :find_it %1

:: Then try all adorned filenames in order.

set mypathext=!pathext!
:loop1
    :: Stop if found or out of extensions.

    if "x!mypathext!"=="x" goto :loop1end

    :: Get the next extension and try it.

    for /f "delims=;" %%j in ("!mypathext!") do set myext=%%j
    call :find_it %1!myext!

:: Remove the extension (not overly efficient but it works).

:loop2
    if not "x!myext!"=="x" (
        set myext=!myext:~1!
        set mypathext=!mypathext:~1!
        goto :loop2
    )
    if not "x!mypathext!"=="x" set mypathext=!mypathext:~1!

    goto :loop1
:loop1end

:end
endlocal
goto :eof

:: Function to find and print a file in the path.

:find_it
    for %%i in (%1) do set fullspec=%%~$PATH:i
    if not "x!fullspec!"=="x" @echo.   !fullspec!
    goto :eof

It actually returns all possibilities but you can tweak it quite easily for specific search rules.

paxdiablo
Hey, I wish I had learned that! Too bad it doesn't work with MS-DOS or Win9x (that is, with command.com). (Raymond Chen has a more "elaborate" version you can turn into a batch file: http://blogs.msdn.com/oldnewthing/archive/2005/01/20/357225.aspx )
crosstalk
@Michael, if you're still using DOS or Win95, finding executables on the path are the *least* of your problems :-)
paxdiablo
windows recognizes more than .exe as executable. Last time I coded a `which` back in W95/DOS days amdittedly, the search order was - current dir, then each path dir, for cmd.com, then cmd.exe, then cmd.bat So, even cmd.bat in current dir is executed befroe cmd.exe soemwhere in path
Mawg
@mawg, the original was for where you know the extension since it mirrors which under UNIX (where that extension-adding trickery doesn't occur). I've now added one which can do what you wish but it's no longer a simple command so much as a script. It first tries the unadorned command then each of the extension ones. Hope that helps. You can tweak it to your needs as you see fit (if you want the same search order as with Windows for example - this one shows all possibilities).
paxdiablo
+18  A: 

Windows Server 2003 and later provide the WHERE command which does some of what which does (though it won't recognize built-in shell commands like cd and matches all types of files, not just executable commands). It will even accept wildcards (so where nt* finds all files in your PATH whose names start with nt). Try where /? for help.

crosstalk
+5  A: 

Michael mentions this - the command in Vista is 'where'

Paul Betts
+4  A: 

The GnuWin32 tools have which, along with a whole slew of other Unix tools.

Ferruccio
A: 

I have created tool similar to Ned Batchelder:

Searching .dll and .exe files in PATH

While my tool is primarly for searching of various dll versions it shows more info (date, size, version) but it do not use PATHEXT (I hope to update my tool soon).

Michał Niklas
A: 

Go get unxutils from here: http://sourceforge.net/projects/unxutils/

gold on windows platforms, puts all the nice unix utilities on a standard windows DOS. Been using it for years.

It has a 'which' included. Note that it's case sensitive though.

Jon

NB: to install it explode the zip somewhere and add ...\UnxUtils\usr\local\wbin\ to your system path env variable.

Jon Court
A: 

Dunno if this helps. Posted as answer because I don't knoe how to format code in comments (help?)

If you can find a free pascal compiler, you can compile this, or email me & I can try to did one out, or mail back the exe or post it somewhere. I post the code, bad as it is, because at least it works & shows the algorithm necessary.

program Whence (input,output);
  Uses Dos, my_funk;
  Const program_version = '1.00';
        program_date    = '17 March 1994';
  VAR   path_str          : string;
        command_name      : NameStr;
        command_extension : ExtStr;
        command_directory : DirStr;
        search_dir        : DirStr;
        result            : DirStr;


  procedure Check_for (file_name : string);
    { check existance of the passed parameter. If exists, then state so   }
    { and exit.                                                           }
  begin
    if Fsearch(file_name,'') <> '' then
    begin
      WriteLn('Dos command = ',Fexpand(file_name));
      Halt(0);    { structured ? whaddayamean structured ? }
    end;
  end;

  function Get_next_dir : DirStr;
    { Returns the next directory from the path variable, truncating the   }
    { variable every time. Implicit input (but not passed as parameter)   }
    { is, therefore, path_str                                             }
    var  semic_pos  : Byte;

  begin
      semic_pos  := Pos(';',path_str);
      if (semic_pos = 0) then
      begin
        Get_next_dir := '';
        Exit;
      end;

      result       := Copy(Path_str,1,(semic_pos - 1));  { return result   }
      { hmm! although *I* never reference a Root drive (my directory tree) }
      { is 1/2 way structured), some network logon software which I run    }
      { does (it adds Z:\ to the path). This means that I have to allow    }
      { path entries with & without a terminating backslash. I'll delete   }
      { anysuch here since I always add one in the main program below.     }
      if (Copy(result,(Length(result)),1) = '\') then
         Delete(result,Length(result),1);

      path_str     := Copy(path_str,(semic_pos + 1),
                                 (length(path_str) - semic_pos));
      Get_next_dir := result;
  end;  { of function get_next_dir }

begin
  { the following is a kludge which makes the funtion Get_next_dir easier  }
  { to implement. By appending a semi-colon to the end of the path         }
  { Get_next_dir doesn't need to handle the special case of the last entry }
  { which normally doesn't have a semic afterwards. It may be a kludge,    }
  { but it's a documented kludge (you might even call it a refinement).    }
  path_str := GetEnv('Path') + ';';

  if (paramCount = 0) then
  begin
    WriteLn('Whence : V',program_version,' from ',program_date);
    Writeln;
    WriteLn('Usage  : WHENCE command[.extension]');
    WriteLn;
    WriteLn('Whence is a ''find file''type utility witha difference');
    Writeln('There are are already more than enough of those   :-)');
    Write  ('Use Whence when you''re not sure where a command which you ');
    WriteLn('want to invoke');
    WriteLn('actually resides.');
    Write  ('If you intend to invoke the command with an extension e.g ');
    Writeln('"my_cmd.exe param"');
    Write  ('then invoke Whence with the same extension e.g ');
    WriteLn('"Whence my_cmd.exe"');
    Write  ('otherwise a simple "Whence my_cmd" will suffice; Whence will ');
    Write  ('then search the current directory and each directory in the ');
    Write  ('for My_cmd.com, then My_cmd.exe and lastly for my_cmd.bat, ');
    Write  ('just as DOS does');
    Halt(0);
  end;

  Fsplit(paramStr(1),command_directory,command_name,command_extension);
  if (command_directory <> '') then
  begin
WriteLn('directory detected *',command_directory,'*');
    Halt(0);
  end;

  if (command_extension <> '') then
  begin
    path_str := Fsearch(paramstr(1),'');    { current directory }
    if   (path_str <> '') then WriteLn('Dos command = "',Fexpand(path_str),'"')
    else
    begin
      path_str := Fsearch(paramstr(1),GetEnv('path'));
      if (path_str <> '') then WriteLn('Dos command = "',Fexpand(path_str),'"')
                          else Writeln('command not found in path.');
    end;
  end
  else
  begin
    { O.K, the way it works, DOS looks for a command firstly in the current  }
    { directory, then in each directory in the Path. If no extension is      }
    { given and several commands of the same name exist, then .COM has       }
    { priority over .EXE, has priority over .BAT                             }

    Check_for(paramstr(1) + '.com');     { won't return if file is found }
    Check_for(paramstr(1) + '.exe');
    Check_for(paramstr(1) + '.bat');


    { not in current directory, search thru path .... }

    search_dir := Get_next_dir;

    while (search_dir <> '') do
    begin
       Check_for(search_dir + '\' + paramstr(1) + '.com');
       Check_for(search_dir + '\' + paramstr(1) + '.exe');
       Check_for(search_dir + '\' + paramstr(1) + '.bat');
       search_dir := Get_next_dir;
    end;


    WriteLn('DOS command not found : ',paramstr(1));
  end;
end.
Mawg
Wow, there are people still using Pascal? :-)
paxdiablo
I imagine that there are. But not me. Did you see the line program_date = '17 March 1994';
Mawg
A: 

Surprised that nobody has mentioned cygwin as a solution yet. If you don't mind using a 3rd-party solution, then cygwin is the way to go.

Cygwin gives you the comfort of *nix in the Windows environment (and you can use it in your Windows command shell, or use a *nix shell of your choice). It gives you a whole host of *nix commands (like which) for Windows, and you can just include that directory in your PATH.

palswim