views:

86

answers:

3

So I recently stumbled on the (potentially) useful %~$PATH:1 expansion, however I seem to be unable to make it work correctly. I tried to use it to make a cheap Windows version of the which command, however the syntax seems to be defeating me. My batch file looks like this:

@echo off
echo %~$PATH:1

However when I run this with for example

which cmd

all I get as output of "ECHO is off.", which means according to the docs that the %~$PATH:1 didn't find "cmd". What am I doing wrong?

A: 

Shoot! I just figured it out! I need to use the full "cmd.exe" as a parameter instead of just "cmd". D'oh! ;] So, the complete which.cmd script looks like this:

@echo off
call :checkpath %1
call :checkpath %1.exe
call :checkpath %1.cmd
call :checkpath %1.bat
:checkpath
if "%~$PATH:1" NEQ "" echo %~$PATH:1

Yeah! Finally a which command on Windows! ;]

HerbCSO
+2  A: 

Checking for files with the extensions .exe, .cmd or .bat is not enough. The set of applicable extensions is defined in the environment variable PATHEXT.

Here is my version of a which command that honors the PATHEXT variable upon search:

@echo off
rem Windows equivalent of Unix which command

setlocal enabledelayedexpansion

if "%~1"=="" (
    echo Usage: which cmdname
    exit /b 1
)

call :findOnPath "%~1"
if not errorlevel 1 exit /b 0
for %%E in (%PATHEXT:;= %) do (
    call :findOnPath "%~1%%E"
    if not errorlevel 1 exit /b 0
)

echo "%~1" not found on PATH.
exit /b 1

:findOnPath
    if not "%~$PATH:1" == "" (
     echo "%~$PATH:1"
     exit /b 0
    )
    exit /b 1
sakra
Very good - I stand corrected. Thanks much.
HerbCSO
A: 

I have been using this one for a while, it also checks built-in commands

Anders