Reputation: 2896
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 ) ) )
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.
Upvotes: 0
Views: 3379
Reputation: 67296
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
)
Upvotes: 2
Reputation: 12296
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.
Upvotes: 2