2017-09-01 5 views
0

Je me suis fait l'écho du code suivant, mais je ne peux pas déterminer pourquoi% ERRORLEVEL% est zéro.Utilisation de% ERRORLEVEL% pour renvoyer une valeur du sous-programme dans le script batch

@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 

je reçois la sortie suivante

0 
0 

mais je pense

0 
1 

et selon l'écho, je l'ai fait à l'intérieur :isInPath pour le cas d'un exit /b 0 et pour le cas de deux exit /b 1 est appelé . Mais pourquoi %ERRORLEVEL% zéro dans tous les deux cas? Je ne comprends absolument pas. S'il vous plaît aider!

Répondre

2

En cmd, la ligne entière sera analysée pour la substitution de variables à la fois. Par conséquent au moment où la ligne suivante est exécutée errorlevel est 0

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

Vous devez utiliser delayed expansion

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

divisant simplement la ligne en deux devrait résoudre le problème sans expansion retardée – Stephan

+0

@Stephan ce serait trop évident –