5

好的,我正在尝试执行几个嵌套的 IF EXIST 语句来检查几个文件夹的存在。如果第一个文件夹存在,请将 Folder1 设置为等于 1,然后跳至安装。与 Folder2 相同,然后如果两个文件夹都不存在,则跳过安装。

但即使 Folder1 不存在,这仍然将 %Folder1% 设置为等于 1。我错过了什么/没有做什么?

谢谢!

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
4

3 回答 3

11

两个基本问题:

复合语句必须用括号括起来。在括号内,更改变量值将不可见,除非您执行了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="

在每个报告的开始和之后执行,确保从环境中删除有问题的环境变量,以防止代码在陈旧信息上给出错误的结果。

于 2013-04-01T17:09:38.210 回答
1
if exist "c:\folder1" (
        set Folder1=1
        echo %Folder1%
        goto install
) if exist "c:\folder2" (
        set Folder2=1
        echo %Folder2%
        goto Install
) else goto Install 

:Install
于 2013-04-01T17:00:07.850 回答
0

如果 folder1 不存在,此代码不会设置 %folder1%=1,并且在这种情况下不会产生任何输出。如果 Folder1 不存在且Folder2存在THEN %folder2% 设置为 1,否则 %folder2% 为空。echo如果变量为空,则在命令后放置一个未闭合的左括号以抑制输出。

@echo off &setlocal
if exist "c:\folder1" set "Folder1=1"
echo(%Folder1%
if not defined Folder1 if exist "c:\folder2" set "Folder2=1"
echo(%Folder2%
goto Install

:Install
endlocal
于 2013-04-01T17:29:59.163 回答