How can I "which <binary>" in cmd.exe

Solution 1:

A cmd.exe one-liner for which would be:

for %G in (<binary.exe>) do @echo.%~$PATH:G

You can code it as a simple which.bat:

@echo off
for %%G in (%1) do @echo.%%~$PATH:G

EDIT: it requires full name of binary: which perl.exe, not which perl. It is possible to write a batch file that takes %PATHEXT% into consideration, so it does not need the full name of binary. Please let me know if you need it.

EDIT2: anyway I decided to write the batch file. Here it is:

@echo off
setlocal enabledelayedexpansion

set ext= ;%PATHEXT%
:extloop1
for /f "delims=; tokens=1,*" %%A in ("!ext!") do (
  if exist %1%%A (
    echo .\%1%%A
    goto finish
  )
  set ext=%%B
)
if "!ext!" neq "" goto extloop1

set ext= ;%PATHEXT%
:extloop2
for /f "delims=; tokens=1,*" %%A in ("!ext!") do (
  for %%C in (%1%%A) do (
    if exist %%~$PATH:C (
      echo %%~$PATH:C
      goto finish
    )
  )
  set ext=%%B
)
if "!ext!" neq "" goto extloop2

:finish
endlocal

First, as per Bob's sugestion, it checks if the binary exists in the current directory. If the binary is not found, another loop is executed which does the search through %PATH% variable.

Loops are based on if ... goto, for command is used only to split the ext value by ';' character. The value of %PATHEXT% is prepended with an empty extension, which allows for searching for fully named binary - both which perl and which perl.exe works.

Solution 2:

You could try Paul Sadowski's collection of utilities - he includes a which. See it at: http://www.paulsadowski.com/wsh/cmdprogs.htm