嵌套如果批处理文件中存在Exist语句

时间:2013-04-01 16:57:54

标签: if-statement batch-file

好的,我正在尝试做几个嵌套的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

3 个答案:

答案 0 :(得分: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="

在每个报告的开始和结束后都会执行此操作,以确保从环境中删除有问题的环境变量,以防止代码在陈旧信息上显示错误结果。

答案 1 :(得分: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

答案 2 :(得分:0)

如果folder1不存在,则此代码不会设置%folder1%= 1,在这种情况下它不会产生输出。如果Folder1不存在 AND 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