使用 %ERRORLEVEL% 到 return 批处理脚本中子例程的值
Using %ERRORLEVEL% to return a value from subroutine in batch script
我一直在重复以下代码,但我无法确定为什么 %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%
在 两个 案例中都是零?我完全不明白。请帮忙!
在 cmd 中,将立即解析整行以进行变量替换。因此在执行以下行时 errorlevel
是 0
call :isInPath %blub% & set foundBlub=%ERRORLEVEL%
您需要使用delayed expansion
SETLOCAL EnableDelayedExpansion
call :isInPath %blub% & set foundBlub=!ERRORLEVEL!
我一直在重复以下代码,但我无法确定为什么 %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%
在 两个 案例中都是零?我完全不明白。请帮忙!
在 cmd 中,将立即解析整行以进行变量替换。因此在执行以下行时 errorlevel
是 0
call :isInPath %blub% & set foundBlub=%ERRORLEVEL%
您需要使用delayed expansion
SETLOCAL EnableDelayedExpansion
call :isInPath %blub% & set foundBlub=!ERRORLEVEL!