Checking if the output is OK

2019-09-03 10:16发布

问题:

I am running a command from the CMD via a batch file like so..

echo Step 3. Check TNSPING
tnsping vtdbs 2>NUL
    if not errorlevel 1 set error=PASSED
    if errorlevel 1 set error=FAILED
echo Result: %error%

But this only tells me if it actually was able to run the command.. When this command is ran it will give an output like so..

blah blah blah
blah blah blah
blah blah
blah blah
blah blah
blah blah
blah blah
OK (80 msec)

So line 8 should say "OK" and as long as it does then.. echo RESULT: Passed else echo RESULT: Failed

But not sure how to check and see if 8th line is .."OK"

回答1:

Here's a more efficient solution, also tolerant if the output of tnsping vtdbs is <> 8 lines.

echo Step 3. Check TNSPING
set "error=FAILED"
for /f %%I in ('tnsping vtdbs 2^>NUL') do (
    if "%%I"=="OK" (set "error=PASSED" & goto next)
)
:next
echo Result: %error%

The reason you don't have to check if %%I matches OK (??ms) is that for /f defaults to "tokens=1" -- or, in other words, assigning %%I to the first word of each line.



回答2:

Try this:

@echo off &setlocal
set "result="
for /f %%i in ('tnsping vtdbs 2^>NUL^|more +7') do if not defined result set "result=%%i"
if "%result%" equ "OK" (set "error=PASSED") else set "error=FAILED"
echo Result: %error%
endlocal