我一直在回答以下代码,但我无法确定为什么%ERRORLEVEL%总是为零。
@echo off
set activePerl_SiteBinPath=D:\ProgramFiles\ActivePerl\site\bin
call :isInPath %activePerl_SiteBinPath% & set foundActivePerl_SiteBinPath=%ERRORLEVEL%
echo %foundActivePerl_SiteBinPath%
set blub=d:\blub
call :isInPath %blub% & set foundBlub=%ERRORLEVEL%
echo %foundBlub%
exit /b
:isInPath
:: Tests if the path stored within variable pathVar exists within %PATH%.
::
:: The result is returned as the ERRORLEVEL:
:: 0 if pathVar is found in %PATH%.
:: 1 if pathVar path is not found in %PATH%.
:: 2 if parhVar path is missing/undefined.
:: Error checking
if "%~1"=="" exit /b 2
set pathVar=%~1
for /f %%i in ('echo ";%%PATH%%;" ^| find /c /i ";%pathVar%;"') do (
set /a foundPathVar=%%i
)
if /i %foundPathVar% equ 0 (
exit /b 1
)
set foundPathVar=0
exit /b 0
我得到以下输出
0
0
但我希望
0
1
并且根据我在:isInPath
内对案例一exit /b 0
所做的回应,并且对于案例二,exit /b 1
被调用。但是为什么两个个案中%ERRORLEVEL%
为零?我完全不明白。请帮忙!
答案 0 :(得分:3)
在cmd中,将立即解析整行以进行变量替换。因此,在执行以下行时errorlevel
为0
call :isInPath %blub% & set foundBlub=%ERRORLEVEL%
您需要使用delayed expansion
SETLOCAL EnableDelayedExpansion
call :isInPath %blub% & set foundBlub=!ERRORLEVEL!