Exist Nested Statements in a Batch File

Ok, I'm trying to make a couple of IF EXIST nested statements to check for folders. If the first folder exists, set Folder1 to 1, and then go to Install. Same thing with Folder2, and then if none of them exist, just skip to install.

But even if Folder1 does not exist, it still sets% Folder1% to 1. What am I missing / not doing?

Thank!

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
+5
source share
3 answers

Two fundamental issues:

The compound statement must be enclosed in parentheses. In parentheses, changing the value of a variable will NOT be visible if you haven’t done so SETLOCAL ENABLEDELAYEDEXPANSION- and even then you will need to use it! Var! not% var%

So:

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="

, , , , , , , , .

+11
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
+1

% folder1% = 1, folder1 , . Folder1 , 2 THEN% 2% ​​ 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
0

All Articles