Search code examples
batch-filecmd

Im trying something with IF in Batch but is not working as im expecting


I need to do an script that looks for some text in a file and also look for a file itself in a %userprofile% path, and it works fine but when i tried to unify it so that instead of outputing 2 confirming messages only output 1, something is not going as expected, this is the code:

hostname > hstnm.txt
SET /p hstnm=<hstnm.txt
SET pccer=.filextension1
SET pcsip=.filextension2
SET fullhost=%hstnm%%pccer%
SET fullsip=%hstnm%%pcsip%
SET fullroute=%userprofile%\thepath\%fullhost%
SET siproute=%userprofile%\thepath\%fullsip%

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
IF %errorlevel%==0 (
 SET siptest="true"
) ELSE (
 SET siptest="false"
)

IF EXIST "%fullroute%" (
 SET certest="true"
) ELSE (
 SET certest="false"
)

IF %siptest%=="true" & %certest%=="true" (
ECHO message if everything good
) ELSE (
ECHO message if something bad
)
pause

The FINDSTR and the IF EXIST are working properly (if u swap SET for an ECHO it does display a message). The problem arrives at the part of using the %certest% and the %siproute%, it is doing nothing, just outputs this (if i quit the @echo off)

...
C:\path>IF EXIST "C:\Users\Administrador\Appdata\Roaming\Interactive Intelligence\PureCloud Softphone\certificates\sip\GSSES0401107C.grupogss.corp.cer" (SET certest="true" )  ELSE (SET certest="false" )
No se esperaba & en este momento.
C:\path>IF "true"=="true" & "true"=="true" (
C:\path>

Help me please! thanks in advance.


Solution

    1. Sometimes we do not need to do parenthesized if's.
    2. There is already a variable containing the hostname called %COMPUTERNAME% which you can use without having to create a temp file
    3. Pre-set variables and only change them if the files do not exist instead of the if else statements.
    4. nested if's do not use &. We simply put the next after the other. if one condition returns true, it will do the next, etc. if any condition fails, it will stop processing the rest of the line and continue to the next line:
    @echo off
    set "pccer=.filextension1"
    set "pcsip=.filextension2"
    set "fullhost=%COMPUTERNAME%%pccer%"
    set "fullsip=%COMPUTERNAME%%pcsip%"
    set "fullroute=%userprofile%\thepath\%fullhost%"
    set "siproute=%userprofile%\thepath\%fullsip%"
    set "siptest=false"
    set "certest=false"
    
    FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
    if not errorlevel 1 set "siptest=true"
    if exist "%fullroute%" set "certest=true"
    
    if "%siptest%" == "true" if "%certest%" == "true" echo message if everything good & goto :done
    echo message if something bad
    
    :done
    pause