0
votes

RESOLVED:

I have a long script that I have condensed to the following lines of code to illustrate the issue I am having. I have tried some suggestion by StackOverflow users to no avail, so hopefully your feedback will help me and future users. NOTE: this code works, except for setting the pdfREP nested variable.

SETLOCAL enabledelayedexpansion
set pdfREP=false

for /f "tokens=1" %%a in ('dir /o /b \\path2document\*.rp?') do (
    findstr "," \\path2log\%%a > 1.log
    if not errorlevel 0 (
        :: do something
        )
    if errorlevel 0 (
        findstr /B /I "p" \\path2document\%%a > 1.log
        if errorlevel == 0 (
            set pdfREP=true
            echo RSP File: %%a >> 2.log 
        )
    )
        echo the value of pdfREP is !pdfREP!
)

Basically the issue is that in \path2document I have multiple files, and within each I look for a comma. If no comma is found then I want to know if there is a particular letter inside the file's text. If the text is found, the I am setting a previously defined variable to TRUE, instead of FALSE. However, the "if errorlevel == 0" can be true if different syntax (%errorlevel%==0,%errorlevel% EQU 0), and it will NOT set the variable pdfREP to TRUE. If the issue is that the variable is not set until after the loop iteration, then how can I use this variable in the rest of my code? I would like to use this variable later on, so setting it is most important. Thanks for any feedback.

RESOLUTION: The variable I was setting was not displaying it current value because I was using delayed expansion and it confused me not to see the value, so it became an issue that wasn't. Since I was using the variable value within the loop, I needed to access the current value of the variable with ! around the variable name, rather than %.

2

2 Answers

2
votes

Windows batch has an "interesting" way of handling nested variables. This article might help.

Personally, when my batch files get this complex, I switch to a different language. My first choice is generally Python, but if you'd like to stay inside the Microsoft ecosystem, then vbscript or PowerShell would work.

2
votes

You are misusing the IF command and the errorlevel value.

IF command description indicate that you may directly use in the condition the ERRORLEVEL word followed by a number indicating a given errorlevel. This way, the following two IF commands are right:

if not errorlevel 0 (
    :: do something
    )
if errorlevel 0 (

However, the following command is bad written:

if errorlevel == 0 (

In this case, you must use !errorlevel! to indicate to take the current errorlevel value after executing the last line:

if !errorlevel! == 0 (

Independently of the above said, this is the way that I would do that:

if not errorlevel 0 (
    echo The errorlevel is less than zero 
) else if errorlevel 0 (
    echo The errorlevel is greater than zero
) else (
    echo The errorlevel is zero
)