我想知道CMD shell使用哪个版本的可执行文件。在任何unix shell中,我都会使用which
来查找它。
其中一个Windows shell中是否有等效的命令?
答案 0 :(得分:65)
各种
where
是直接等效的:
C:\Users\Joey>where cmd
C:\Windows\System32\cmd.exe
请注意,在PowerShell中where
本身是Where-Object
的别名,因此您需要在PowerShell中使用where.exe
。
在cmd
中,您还可以使用for
:
C:\Users\Joey>for %x in (powershell.exe) do @echo %~$PATH:x
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
在PowerShell中,您有Get-Command
及其别名gcm
,如果您传递参数(但也适用于PowerShell中的别名,cmdlet和函数),它们也会这样做:
PS C:\Users\Joey> Get-Command where
CommandType Name Definition
----------- ---- ----------
Alias where Where-Object
Application where.exe C:\Windows\system32\where.exe
第一个返回的命令是将要执行的命令。
答案 1 :(得分:4)
WHERE
命令与unix which
不完全相同,因为它列出了当前目录或PATH中找到的所有匹配文件。正如乔伊所说,列出的第一个是执行的那个。创建一个只返回第一个找到的批处理脚本很简单。
@echo off
for /f "delims=" %%F in ('where %1') do (
echo %%F
exit /b
)
但是WHERE
相对较慢。
下面是一个更快且更多的WHICH.BAT脚本。它使用广泛的延迟扩展切换,因为:1)如果有不带引号的特殊字符,扩展%PATH%是不可靠的。 2)启用延迟扩展时扩展FOR变量会破坏包含!
的值。
::WHICH.BAT CommandName [ReturnVar]
::
:: Determines the full path of the file that would execute if
:: CommandName were executed.
::
:: The result is stored in variable ReturnVar, or else it is
:: echoed to stdout if ReturnVar is not specified.
::
:: If no file is found, then an error message is echoed to stderr.
::
:: The ERRORLEVEL is set to one of the following values
:: 0 - Success: A matching file was found
:: 1 - CommandName is an internal command
:: 2 - No file was found and CommandName is not an internal command
:: 3 - Improper syntax - no CommandName specified
::
@echo off
setlocal disableDelayedExpansion
set "file=%~1"
setlocal enableDelayedExpansion
if not defined file (
>&2 echo Syntax error: No CommandName specified
exit /b 3
)
:: test for internal command
echo(!file!|findstr /i "[^abcdefghijklmnopqrstuvwxyz]" >nul || (
set "empty=!temp!\emptyFolder"
md "!empty!" 2>nul
del /q "!empty!\*" 2>nul >nul
setlocal
pushd "!empty!"
set path=
(call )
!file! /? >nul 2>nul
if not errorlevel 9009 (
>&2 echo "!file!" is an internal command
popd
exit /b 1
)
popd
endlocal
)
:: test for external command
set "noExt="
if "%~x1" neq "" if "!PATHEXT:%~x1=!" neq "!PATHEXT!" set noExt="";
set "modpath=.\;!PATH!"
@for %%E in (%noExt%%PATHEXT%) do @for %%F in ("!file!%%~E") do (
setlocal disableDelayedExpansion
if not "%%~$modpath:F"=="" if not exist "%%~$modpath:F\" (
endlocal & endlocal & endlocal
if "%~2"=="" (echo %%~$modpath:F) else set "%~2=%%~$modpath:F"
exit /b 0
)
endlocal
)
endlocal
>&2 echo "%~1" is not a valid command
exit /b 2
<强>更新强>
我必须对上面的脚本进行重大修改,因为如果在PATH中某处存在一个具有相同根名称的exe文件,它会错误地将内部命令列为外部命令。