查找将从Windows命令行执行的程序的路径

Finding the path of the program that will execute from the command line in Windows

假设我在系统的c:\abcd\happy\文件夹中安装了一个程序X.EXE。文件夹在系统路径上。现在假设系统上有另一个程序,也称为x.exe,但安装在c:\windows\文件夹中。

是否可以从命令行中迅速发现,如果我输入X.EXE,两个X.EXE中的哪一个将被启动?(但不必在任务管理器中直接搜索或查看流程详细信息)。

也许是某种内置的命令,或者是一些可以做这种事情的程序?:

1
detect_program_path X.EXE


使用where命令。列表中的第一个结果是将要执行的结果。

1
2
3
4
5
C:\> where notepad
C:\Windows\System32
otepad.exe
C:\Windows
otepad.exe

根据这篇博文,where.exe包含在WindowsServer2003和更高版本中,因此这应该只适用于Vista、Win7等。

在Linux上,相当于which命令,例如which ssh


下面是一个小的命令脚本,您可以将-n-paste复制到一个名为where.cmd的文件中:

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
@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem    The main ideas for this script were taken from Raymond Chen's blog:
rem
rem         http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem     help diagnose situations with a conflict of some sort.
rem

setlocal

rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%

if not"%EXTLIST%" =="" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok

rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT"%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT"%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i


正如注释中提到的线程,PowerShell中的get-command也可以解决这个问题。例如,您可以键入get-command npm,输出如下:

enter image description here