Which.bat for windows command shell


In linux, the which command is to search for executables in the given $PATH variables. [This command is useful for finding out “which” binary the system would execute if you were to type the command out. Since some programs have multiple versions installed the which command comes in handy to tell you which version it is using and where it is located.]

In windows, the which command can be easily created simply a few lines of code in batch script, which are well supported from Windows 2000 and afterwards.

I have created a new repo and upload the batch script file in https://github.com/DoctorLai/BatchUtils

Below is the source code of this batch utility.

@Echo Off
Rem https://helloacm.com, 25-May-2012

If [%1]==[] Goto USAGE

:LOOP
  If [%1]==[] Goto END

:CHECK
  SetLocal
    Set Paths=.;%PATH%
    For %%E In (%PATHEXT%) Do (
      For %%I In ("%~n1%%E") Do (
        If NOT "%%~$Paths:I"=="" Echo %%~$Paths:I
      )
    )
  EndLocal
  Shift
  Goto LOOP

:USAGE
  Echo %0 [Executable1] [Executable2] ..

:END

Below is the usage example, you can put multiple files to search in the path.

which Which.bat for windows command shell batch script beginner implementation technical windows command shell

The shift keyword is to used in the batch script to make %1 = %2, %2 = %3… in other words, each parameter is shift one to the left.

The environment variable %PATHEXT% contains a list of executable file extensions, for example, .EXE .COM .BAT etc.

The %~n1 “extracts the filename from %1, without the extension.

[SETLOCAL on it’s own, usually at the start of a batch file, will begin localisation of Environment Variables.

Issuing a SETLOCAL command, the batch script will inherit all current variables from the master environment/session.

If a batch script does not use SETLOCAL and ENDLOCAL then all variables will be Global, i.e. visible and modifiable by other scripts]

Related Posts

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
395 words
Last Post: Codeforces: A. Football
Next Post: Codeforces: A. Young Physicist

The Permanent URL is: Which.bat for windows command shell

Leave a Reply