2017-09-01 62 views
0

我一直在迴應以下代碼,但我無法確定爲何%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%爲零均爲個案?我完全不明白。請幫忙!

回答

2

在cmd中,整行將一次性解析變量替換。因此,在當時以下行執行errorlevel爲0

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

您需要使用delayed expansion

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

簡單地分割線分成兩個要解決問題,而推遲擴張 – Stephan

+0

@Stephan那樣太明顯 –

相關問題