Linux `which` 命令可在 `$PATH` 中尋找可執行檔完整路徑。Windows 原生無此命令,Resource Kit 提供 `where.exe` 但需付費。本文提供純批次檔 `which.bat` 實作,放入 PATH 目錄即可在 `cmd.exe` / PowerShell 中直接使用。
@echo off
REM ===== which.bat : 模擬 Linux which 命令 =====
REM 用法: which "command_name"
REM 回傳: 找到的第一個完整路徑,若找不到輸出錯誤並回傳非 0
REM 1. 參數檢查
if {%1}=={} goto :Usage
REM 2. 排除帶有幫助旗標的呼叫
for %%i in (/? /h /help -?) do if "%~1"=="%%i" goto :Usage
REM 3. 先檢查當前目錄 (含副檔名自動補全 PATHEXT)
for %%i in (%1) do if exist "%%~fi" (
echo %%~fi
goto :EOF
)
REM 4. 遍歷 PATH 環境變數尋找
for %%i in (%1) do (
if exist "%%~$PATH:i" (
echo %%~$PATH:i
goto :EOF
)
)
REM 5. 找不到
echo Error: "%~1" not found in PATH!
exit /b 1
:Usage
echo.
echo WHICH "command_name"
echo.
echo Searches PATH for the executable and prints the full path of the first match.
echo.
exit /b 1
| 語法 | 說明 |
|---|---|
| `%~1` | 移除參數外層引號 (如有)。 |
| `%%~fi` | 將 `%%i` 擴充為**完整路徑** (含磁碟機、目錄、檔名、副檔名)。 |
| `%%~$PATH:i` | **批次檔獨有擴充**:在 `PATH` 環境變數所列目錄中搜尋 `%%i`,找到則回傳完整路徑,否則為空字串。這是實現 `which` 核心的關鍵。 |
| `PATHEXT` | 系統環境變數,定義可執行檔副檔名順序 (`.EXE;.BAT;.CMD;.COM;...`),`exist` 檢查會自動嘗試附加這些副檔名。 |
C:\>which cmd.exe
C:\Windows\System32\cmd.exe
C:\>which notepad
C:\Windows\System32\notepad.exe
C:\>which nonexistentcmd
Error: "nonexistentcmd" not found in PATH!
PowerShell 內建 `Get-Command` (別名 `gcm`) 功能更強:
PS> gcm cmd.exe
CommandType Name Version Source
----------- ---- ------- ------
Application cmd.exe 10.0.22621 C:\Windows\System32\cmd.exe
PS> (gcm cmd.exe).Source
C:\Windows\System32\cmd.exe
可在 PowerShell Profile 中建立別名 `Set-Alias which Get-Command` 習慣 Linux 操作。
@echo off
REM which-all.bat : 列出 PATH 中所有同名可執行檔
if {%1}=={} goto :Usage
for %%i in (%1) do (
set "found="
for %%p in ("%%~$PATH:i") do (
if not defined found (
echo %%~p
set found=1
) else (
echo %%~p
)
)
if not defined found echo Error: "%~1" not found in PATH! && exit /b 1
)
goto :EOF
:Usage
echo Usage: which-all "command_name"
exit /b 1
利用批次檔參數擴充修飾符 `%%~$PATH:i` 可輕鬆在 Windows 實現 `which` 功能,無需外部工具。理解 `PATHEXT`、參數修飾符、環境變數遍歷機制,有助於編寫更健壯的跨平台建構腳本與開發工具鏈。