WettDawg
WettDawg

Reputation: 13

'if errorlevel' statement when in 'for findstr' loop

I have been unsuccessful getting the following to work. Everything works until I try to get the results of the 'findstr' in the 'for' loop. Maybe there is a better way of doing this: look for %subnet% in the masters.csv file. If it finds it, set the MSS variable to the resulting value from the 'for'. If it does not find a value, it will assign a static value (orphan). Thanks in advance for any help!!

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
        set ip=%ip:~1%
        echo %ip% > ipaddress.txt
        pause
        for /F "tokens=1-3 delims=." %%a in ("%ip%") do set FirstThreeOctets=%%a.%%b.%%c
        @REM echo First three: %FirstThreeOctets%
        @echo off
        setlocal
        set subnet=%FirstThreeOctets%
        echo %subnet%
        for /f "tokens=2 delims=," %%A in ('findstr /r "^%subnet%," "\\server\APPS\appname\updates\masters.csv"') do goto OrphanCheck
        @REM if errorlevel ==1 goto Orphan do set MSS=%%A
        @REM echo %MSS%
        @REM goto 64installcheck
    :OrphanCheck
        if errorlevel==1 goto Orphan
        Goto NoOrphan
        :NoOrphan
        set MSS=%%A
        Goto 64installcheck
        :Orphan
        set MSS=ORPHAN
        echo %MSS%
        pause

Upvotes: 1

Views: 713

Answers (1)

MC ND
MC ND

Reputation: 70943

When you run

for /f "tokens=2 delims=," %%A in (
    'findstr /r "^%subnet%," "\\server\APPS\appname\updates\masters.csv"'
) do goto OrphanCheck

two things can happen.

If findstr does not find the string, code in for loop is not executed and the next line is reached, but this line does not have access to the errorlevel generated by the findstr, it sees the errorlevel (?) of the for command.

If findstr finds the string, the goto is executed but the same scenario happens.

When the line that checks the error level is reached, another problem raises

if errorlevel==1

is a valid construct, but it does not do what it seams. It is testing if the string errorlevel is equal to the string 1. The correct sintax should be

if errorlevel 1 ....

or

if %errorlevel%==1

but as indicated, when the line is reached the errorlevel will not reflect the error of the findstr command.

And three lines later the next error.

set MSS=%%A

Once the for command has ended, its replaceable parameter does not have any value.

For a simplified version of your code

for /f "tokens=3-6 delims=.: " %%a in ('ipconfig ^| find "IPv4"') do (
    set "ip=%%a.%%b.%%c.%%d"
    set "subnet=%%a.%%b.%%c"
)

>"ipaddress.txt" echo %ip%

for /f "tokens=2 delims=," %%a in (
    'findstr /b /c:"%subnet%," "\\server\APPS\appname\updates\masters.csv"'
) do (
    set "MSS=%%a"
    goto 64installcheck
)

set "MSS=ORPHAN"
echo %MSS%
pause

Upvotes: 2

Related Questions