Windows命令行中是否有与 'which' 等效的命令

Windows命令行中是否有与 ‘which’ 等效的命令

技术背景

在Unix/Linux系统中,which 命令用于查找并显示某个命令的完整路径。而在Windows系统的命令行环境下,没有直接与之等效的 which 命令,但有多种方法可以实现类似的功能。

实现步骤

使用Windows PowerShell的 Get-Command cmdlet

Get-Command 能够查找并列出各种类型的命令,包括可执行文件、cmdlet、函数、别名等。

1
2
3
4
5
6
7
# 查找特定命令
Get-Command eventvwr
# 查找包含特定部分名称的命令
Get-Command *disk*
# 自定义别名使用
Set-Alias which Get-Command
which foo

使用Windows的 where.exe 程序

where.exe 类似于Unix的 which,可以显示与你输入的文件名匹配的完整路径,还能显示所有匹配的路径。

1
2
3
4
5
6
C:\> where edit
C:\Windows\System32\edit.com

C:\> where notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe

where.exe 还支持通配符:

1
2
3
4
C:\> where nt*.exe
C:\Windows\System32\ntoskrnl.exe
C:\Windows\System32\ntprint.exe
C:\Windows\System32\ntvdm.exe

Windows XP环境下使用环境变量修饰符

1
2
3
4
5
c:\> for %i in (cmd.exe) do @echo.   %~$PATH:i
C:\WINDOWS\system32\cmd.exe

c:\> for %i in (python.exe) do @echo. %~$PATH:i
C:\Python25\python.exe

自定义批处理脚本

以下是一个处理 PATHEXT 中所有扩展名的批处理脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@echo off
setlocal enableextensions enabledelayedexpansion

:: Needs an argument.
if "x%1"=="x" (
echo Usage: which ^<progName^>
goto :end
)

:: First try the unadorned filenmame.
set fullspec=
call :find_it %1

:: Then try all adorned filenames in order.
set mypathext=!pathext!
:loop1
:: Stop if found or out of extensions.
if "x!mypathext!"=="x" goto :loop1end

:: Get the next extension and try it.
for /f "delims=;" %%j in ("!mypathext!") do set myext=%%j
call :find_it %1!myext!

:: Remove the extension (not overly efficient but it works).
:loop2
if not "x!myext!"=="x" (
set myext=!myext:~1!
set mypathext=!mypathext:~1!
goto :loop2
)
if not "x!mypathext!"=="x" set mypathext=!mypathext:~1!

goto :loop1
:loop1end

:end
endlocal
goto :eof

:: Function to find and print a file in the path.
:find_it
for %%i in (%1) do set fullspec=%%~$PATH:i
if not "x!fullspec!"=="x" @echo. !fullspec!
goto :eof

核心代码

使用PowerShell查找自定义可执行文件

1
2
3
4
# 临时修改PATHEXT环境变量
$Env:PATHEXT="$Env:PATHEXT;.dll;.ps1;.psm1;.py"
# 查找自定义可执行文件
Get-Command user32,kernel32,*WASM*,*http*py

简单的批处理查找命令

1
@for %%f in (%*) do for %%e in (%PATHEXT% .dll .lnk) do for %%b in (%%f%%e) do for %%d in (%PATH%) do if exist %%d\%%b echo %%d\%%b

最佳实践

  • 如果你经常使用PowerShell,建议使用 Get-Command 或自定义别名 which,它功能强大,能处理多种类型的命令。
  • 对于简单的查找需求,where.exe 是一个方便的选择,它遵循Windows命令外壳的规则。
  • 在Windows XP环境下,使用环境变量修饰符是一种无需额外工具的解决方案。

常见问题

PowerShell中 wherewhere.exe 的混淆

在PowerShell中,whereWhere-Object cmdlet 的别名,与 where.exe 功能不同。使用 where.exe 时需完整输入。

工具不支持Windows PATHEXT变量

部分从Unix移植过来的 which 工具可能不支持Windows的 PATHEXT 变量,导致无法正确查找某些类型的文件。可以使用上述提到的 Get-Command 或自定义脚本解决。


Windows命令行中是否有与 'which' 等效的命令
https://119291.xyz/posts/2025-05-12.equivalent-of-which-on-windows-command-line/
作者
ww
发布于
2025年5月12日
许可协议