I’ve implemented GNU which as a batch script for Windows. GNU which is a utility that is used to find which executable (or alias or shell function) is executed when entered on the shell prompt. Which.cmd does a similar job for windows: it finds which application or script is executed when you execute a command. It works by going through the list of executable extension in the “%PATHEXT%” environment variable and then searches through the “%PATH%” environment variable for a file with the name you provide on the command line for each extension. When it finds a match, it is displayed, when it finds nothing, it reports an error.
Example:
C:\>which explorer
C:\Windows\explorer.exe
C:\>which cmd.exe
C:\Windows\System32\cmd.exe
C:\>which nc
C:\Tools\nc.exe
C:\>which blablablabla
“blablablabla” not found
You can download the batch script here.


3 Comments to “GNU which for Windows: which.cmd”
2009/09/07
I found a small problem, which only occurs if the expanded path of a program includes parentheses (e.g. “Program Files (x86)”) – line 29 (IF…) balks at them. I fixed it by changing it to:
IF “%~d$PATH:1″==”" (
I also had to remove the ELSE and parentheses that followed, for the same reason.
Apart from this hiccup, great script! It will forever be in my path.
2009/09/07
Thank you for the feedback. I’ve implemented a fix that uses the “short name” to remove any parenthesis when checking the path as well as puts quotes around the path when it is ECHO-ed. This should fix the problem (I’ve tested it on my Vista x64):
:FIND &:: Arguments = “name”
IF “%~s$PATH:1″==”" (
:: The name cannot be found in the PATH variable, return exit code 1
EXIT /B 1
) ELSE (
:: Found: print the full path and return exit code 0
ECHO “%~$PATH:1″
EXIT /B 0
)
I’ve update the download with these changes, you can download the script (again) from the link above to get the new version.
2009/09/09
Nice script, although on Vista and later they added the ‘where’ command which does the same thing
Shame MS don’t publicise these things (or for that matter just called it ‘which’ although to be fair the name ‘where’ makes more sense).
Leave a Comment