下面的命令,给定一个命令的文件名(不包含扩展名),可以自动搜索Path路径中是否存在对应的命令 ,并自动返回完整路径。
例如 which notepad返回C:\Windows\System32\notepad.exe
which.bat 内容:
- @rem Taken from http:
- @echo off
- REM 下面这句是原始的代码: which notepad
- for %%e in (%PATHEXT%) do for %%i in (%1%%e) do if NOT "%%~$PATH:i"=="" echo %%~$PATH:i & goto end
- REM 下面这句是为了兼容处理输入后缀名的情况: which notepad.exe
- for %%d in ("%path:;=" "%") do if exist %%~d\%1 echo %%~d\%1 & goto end
- :end
which.bat
- @echo off
- setlocal enabledelayedexpansion
- rem 文件后缀优先级列表
- set extensions=exe com cmd bat
- rem 获取参数,支持不输入后缀的情况
- set arg=%~1
- if "%arg:~-4%" == ".exe" (
- set name=%arg%
- set has_ext=1
- ) else if "%arg:~-4%" == ".com" (
- set name=%arg%
- set has_ext=1
- ) else if "%arg:~-4%" == ".cmd" (
- set name=%arg%
- set has_ext=1
- ) else if "%arg:~-4%" == ".bat" (
- set name=%arg%
- set has_ext=1
- ) else (
- set name=%arg%
- set has_ext=0
- )
- rem 循环遍历 PATH 中的目录
- for %%d in ("%path:;=" "%") do (
- rem 拼接出要查找的文件名,支持输入后缀的情况
- if !has_ext! == 1 (
- set file=%%~d\%name%
- ) else (
- for %%e in (%extensions%) do (
- set file=%%~d\%name%.%%e
- if exist "!file!" goto found
- )
- )
- if exist "!file!" goto found
- )
- rem 如果没有找到,则输出错误信息
- echo %1 not found
- goto end
- :found
- echo !file!
- :end
which.bat 的另外一个简短版本: