[英]How to test if cmd.exe command exists?
作为例子,在Windows 7 mklink
可从cmd.exe /C mklink
但是在Windows XP事实并非如此。
除了执行cmd.exe /C mklink
并试图读取errorlevel
是有测试更简单的方法,如果CMD.EXE支持命令?
谢谢!
cmd
的ERRORLEVEL
不能很好地指示命令是否存在,因为如果命令不存在或失败,则将其设置为非零值,这可能会使您的测试失败。
或者,您可以执行以下任一操作:
就像Adriano在评论中建议的那样,可以像这样检查Windows版本:
set mklink_supported=true
ver | find "XP" >nul 2>&1 && set mklink_supported=false
或像这样:
set mklink_supported=false
echo %vers% | find "Windows 7" >nul 2>&1 && set mklink_supported=true
然后:
if %mklink_supported%==false (
echo 'mklink' is not supported on this operating system.
)
或类似的东西。 不过,您需要确保正在处理所有必需的OS版本。
ERRORLEVEL
或者,您可以尝试直接运行mklink
。 如果未找到,则将ERRORLEVEL
设置为9009
:
@echo off
mklink >nul 2>&1
if errorlevel 9009 if not errorlevel 9010 (
echo 'mklink' is not supported on this operating system.
)
请注意,有两个if
语句。 if errorlevel 9009
作品如果ERRORLEVEL
> = 9009,因此第二if
需要语句来排除的情况下,当ERRORLEVEL
> 9009)。
我更喜欢第二种解决方案,因为它有望在所有版本的Windows上运行。
要找到可执行文件,可以在for
循环中使用变量扩展:
setlocal EnableDelayedExpansion
set found=no
for %%f in (mklink.exe) do if exist "%%~$PATH:f" set found=yes
echo %found%
endlocal
@echo off
(for /f %%F in ('help') do echo '%%F ')|findstr /i /c:"%1 " 2>&1 >nul && echo Supported || echo Not supported
这取决于一个事实,即help
似乎包括相当完整的内部命令列表(以及相当多的外部命令)。 它期望命令名称作为参数( isSupported.bat command_name
)
它实际上不会测试给定命令是否执行,只有在应该存在的情况下...
这只是一个想法,请尝试使其无效,如果您这样做,我会很乐意删除。
我不久前在SS64 Windows CMD Shell论坛上发布了此批处理脚本 。 它将wmz和Ansgar Wiechers答案中发现的想法组合到一个方便的程序包中。
它尝试在PATH中的某个位置找到给定的可执行文件,然后如果找不到则搜索HELP。 如果缺少HELP涵盖的标准实用程序,它会给出错误的结果并显示一些难看的错误消息。
::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 - No file was found and 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"
if not defined file (
>&2 echo Syntax error: No CommandName specified
exit /b 3
)
set "noExt="
setlocal enableDelayedExpansion
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
>nul help %~1 && (
>&2 echo "%~1" is not a valid command
exit /b 2
)
>&2 echo "%~1" is an internal command
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.