Last active
March 13, 2020 21:28
-
-
Save eschen42/dec433b73edf5090c62ffe854604bdf6 to your computer and use it in GitHub Desktop.
which for Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @set ERRORLEVEL=&setlocal&echo off | |
| :: ref: https://gist.github.com/eschen42/dec433b73edf5090c62ffe854604bdf6 | |
| set ARG1=%1 | |
| if not defined ARG1 ( | |
| echo usage: "%~nx0" executable-name [/a] | |
| exit /b -87 | |
| ) | |
| set ALL=FALSE | |
| set ARG2=%2 | |
| if defined ARG2 ( | |
| set ARG2=%ARG2:"=% | |
| if /i "%ARG2:~0,2%" == "/a" (set ALL=TRUE) | |
| ) | |
| :: make sure that there are no occurrences of ;; in target | |
| set target=%PATH:;;=;%_END | |
| :: make sure that target does not end with a semicolon | |
| set target=%target:;_END=_END% | |
| set target=%target:_END=% | |
| :: prepend current directory and substitute dquote-space-dquote for ; | |
| set target="." "%target:;=" "%" | |
| :: reset found flag | |
| set FOUND=FALSE | |
| :: walk the path looking for a name matching the first arg | |
| for %%h in ( %target% ) do ( | |
| if exist "%%~h\%~1" ( | |
| :: arg1 exactly matches | |
| echo "%%~h\%~1" | |
| if %ALL% == FALSE exit /b 0 | |
| set FOUND=TRUE | |
| ) else if exist "%%~h\%~n1.*" ( | |
| :: arg1 filename matches some files in the directory | |
| for %%i in ( "%%~h\%~n1.*" ) do ( | |
| echo "%%i" | |
| if %ALL% == FALSE exit /b 0 | |
| set FOUND=TRUE | |
| ) | |
| ) | |
| ) | |
| if %FOUND% == TRUE exit /b 0 | |
| exit /b -1 | |
| REM Changes: | |
| REM March 2020 - added the /a option | |
| REM March 2020 - put into double quotes all data traceable to unvalidated user input |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment