Is there an equivalent of 'which' on the Windows command line?
Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the where.exe
program which does some of what which
does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like cd
.) It will even accept wildcards, so where nt*
finds all files in your %PATH%
and current directory whose names start with nt
.
Try where /?
for help.
Note that Windows PowerShell defines where
as an alias for the Where-Object
cmdlet, so if you want where.exe
, you need to type the full name instead of omitting the .exe
extension. Alternatively, you can set an alias for it:
Set-Alias which where.exe
Update: Using Get-Command
(alias: gcm
) is recommended since it's native to PS and will get all command types: aliases, cmdlets, executables, and functions. Example:
gcm notepad*
While later versions of Windows have a where
command, you can also do this with Windows XP by using the environment variable modifiers, as follows:
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
You don't need any extra tools and it's not limited to PATH
since you can substitute any environment variable (in the path format, of course) that you wish to use.
And, if you want one that can handle all the extensions in PATHEXT (as Windows itself does), this one does the trick:
@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
It actually returns all possibilities but you can tweak it quite easily for specific search rules.