使用%ERRORLEVEL%从批处理脚本中的子例程返回值

时间:2017-09-01 15:53:20

标签: batch-file subroutine 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%为零?我完全不明白。请帮忙!

1 个答案:

答案 0 :(得分:3)

在cmd中,将立即解析整行以进行变量替换。因此,在执行以下行时errorlevel为0

call :isInPath %blub% & set foundBlub=%ERRORLEVEL%

您需要使用delayed expansion

SETLOCAL EnableDelayedExpansion
call :isInPath %blub% & set foundBlub=!ERRORLEVEL!