user3581307
user3581307

Reputation: 23

How to loop through files in a directory using batch script

I'm relatively new to batch scripting, I need a script which loops through a directory which has 3 log files and checks for errors and warnings. I'm not very clear on the looping bit. I have written a small code .. help me in correcting it...

for %%a IN ("C:\Program Files (x86)\<installloc>\*.log*")
do
findstr /c:"0 Warnings" %%a
set result1=%errorlevel%

findstr /c:"0 NonFatalErrors" %%a
set result2=%errorlevel%

findstr /c:"0 FatalErrors" %%a
set result3=%errorlevel%
done


if %result1%  & %result2% & %result3% EQU 0 
(
exit 0
) else (
exit 1
)

Upvotes: 0

Views: 4298

Answers (2)

user3581307
user3581307

Reputation: 23

Thank u so much for your reply. It really helped :)... What if i want to add 1 exception for 2 non-fatal errors reason "the process is in use" . Basically it is a known issue and I want the script to ignore it if the message says "process is in use".

Upvotes: 1

MC ND
MC ND

Reputation: 70941

This is what i think you are trying to do

for %%a IN ("C:\Program Files (x86)\<installloc>\*.log*") do (
    for %%b in (Warnings NonFatalErrors FaltalErrors) do (
        findstr /l /c:"0 %%b" "%%~fa"
        if errorlevel 1 exit /b 1
    )
)
exit /b 0

This will search all the files in the folder for any of the indicated strings. If any of them is not found, then exit with errorlevel 1. If all string are found in all files, then, exit with errorlevel 0

This code will fail if you have 10 Warnings (an example), as the searched text is found. Search string must be better defined depending on real file content. Or, if the search text is placed at the start of the line, you can add /b to the findstr command to indicate that the matches should happen at the beginning of the line.

In your original code there are some problems:

In batch files, the closing parenthesis for the set in for command (for ... in (set)) must be in the same line that the do keyword, and the block of lines in the for command (if there are more than one) must be enclosed in parenthesis, so the parser can know which of the lines are intended to be repeated. And the open parenthesis of this block must be in the same line that the do keyword.

Also, there is not AND operator in batch if command. If you want to keep your original sintax, it should be written as

if condition if condition if condition command

and then, command will only be executed when the three conditions evaluate to true.

Upvotes: 0

Related Questions