【问题标题】:Using %ERRORLEVEL% to return a value from subroutine in batch script使用 %ERRORLEVEL% 从批处理脚本中的子例程返回值
【发布时间】:2017-09-01 15:53:19
【问题描述】:

我一直在重复以下代码,但我无法确定为什么%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% 在两种 情况下都为零?我完全不明白。请帮忙!

【问题讨论】:

    标签: batch-file cmd subroutine errorlevel


    【解决方案1】:

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

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

    你需要使用delayed expansion

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

    【讨论】:

    • 只需将行一分为二即可解决问题而不会延迟扩展
    • @Stephan 太明显了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2013-01-07
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    相关资源
    最近更新 更多