Find command gives wrong errorlevel

I need to run a command to find a string in a txt file and if it exists echo Found to either another txt file or the screen.

The problem is I get inconsistent errorlevels. I have output the wmic qfe to a file named wmicinfo.txt.  I then run the command below and get one output the firsttime, then a different output thereafter.

run 1st time...
type wmicinfo.txt | find /c "KB3999999" | echo %errorlevel%

run 2nd time and 3rd and so on...
type wmicinfo.txt | find /c "KB3999999" | echo %errorlevel%
Who is Participating?
Steve KnightConnect With a Mentor IT ConsultancyCommented:
You can also do more than one item in brackets based on the find using && and || e.g.

find /c "KB3999999" < wmcinfo.txt && (
  echo It has been found
  echo DO this
) || (
  echo Do somehing else

Steve KnightIT ConsultancyCommented:
OK this is because the whole line is interpreted in one go so the %errorlevel% isn't set until the next line.  You can probably either do this with delayed expansion:

@echo off
setlocal enabledelayedexpansion
type wmicinfo.txt | find /c "KB3999999" | echo !errorlevel!

or maybe neater?

@echo off
find /c "KB3999999" < wmicinfo.txt && echo Found

The || will run the next command based on a fail (errorlevel 1+) or && will run it based on success (0)


[Edit, sorry put || instead of &&]
Bill PrewCommented:
And just to spice it up a bit, you can also get away from the whole error level checking.  Since you are just looking for the count you can check that value and act accordingly, like below.  Lots of ways to approach this...

for /f %%A in ('find /c "KB3999999" ^< wmcinfo.tx') do (
  if %%A == 0 (
    echo NOT FOUND
  ) else (
    echo FOUND

Open in new window

cavalierlanAuthor Commented:
I used the second post.  It worked perfect.  I changed a little to get it to work in my for loop but otherwise turned out consistent results.

I was looking for error checking because I wanted to echo the KBnumber with either the Found or didn't Find results in my for loop.
Steve KnightIT ConsultancyCommented:
Thanks, glad it helped..... always a million different obscure ways to do the same thing in batch!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.