两个基本问题:
复合语句必须用括号括起来。在括号内,更改变量值将不可见,除非您执行了SETLOCAL ENABLEDELAYEDEXPANSION
- 并且即使这样您也需要使用 !var! 不是 %var%
所以:
SETLOCAL ENABLEDELAYEDEXPANSION
if exist "c:\folder1" (
set Folder1=1
echo !Folder1!
goto install
) else if exist "c:\folder2" (
set Folder2=1
echo !Folder2!
goto Install
) else goto Install
:Install
或者最好是,
@ECHO off
if exist "c:\folder1" (
set Folder1=1
goto install
) else if exist "c:\folder2" (
set Folder2=1
goto Install
) else goto Install
:Install
SET folder
或者更简单
@ECHO off
if exist "c:\folder1" set Folder1=1&goto install
if exist "c:\folder2" set Folder2=1&goto Install
:Install
SET folder
测试:
@ECHO OFF
setlocal
SET "folder1="
SET "folder2="
ECHO.----------No folders
DIR /b /ad c:\folder*
CALL :test
ECHO.----------Folder 1 only
MD c:\folder1
DIR /b /ad c:\folder*
CALL :test
ECHO.----------Folder 2 only
RD c:\folder1
MD c:\folder2
DIR /b /ad c:\folder*
CALL :test
ECHO.----------Both
MD c:\folder1
DIR /b /ad c:\folder*
CALL :test
RD c:\folder1
RD c:\folder2
GOTO :eof
:test
if exist "c:\folder1" set Folder1=1&goto install
if exist "c:\folder2" set Folder2=1&goto Install
:Install
SET folder
SET "folder1="
SET "folder2="
GOTO :eof
此测试创建和删除有问题的两个目录。
结果如下:
----------No folders
----------Folder 1 only
folder1
Folder1=1
----------Folder 2 only
folder2
Folder2=1
----------Both
folder1
folder2
Folder1=1
注意
SET "folder1="
SET "folder2="
在每个报告的开始和之后执行,确保从环境中删除有问题的环境变量,以防止代码在陈旧信息上给出错误的结果。