Home > database >  Single Line FOR /F command FINDSTR error handling unexpected results
Single Line FOR /F command FINDSTR error handling unexpected results

Time:04-06

Problem defined is to have a command line that takes the output of nslookup from a FOR /F loop and either sends to the IP Address to a text file or sends a error message.

The simplest iteration I have is:

FOR /F "skip=3 usebackq tokens=1*" %a IN (`^"nslookup ADROOT02.adroot.the-server-company.co.za 2^>^&1^"`) DO @echo %a | findstr /C:"Address" >nul 2>&1 && echo found || echo not found

However, this only works if an address is found, but no output is received if the findstr fails; i.e. no || echo not found is not activated for some reason.

I am looking for assistance is finding the issue/resolution to have a single command line executable that can define the IP addresses.

CodePudding user response:

@ECHO OFF
SETLOCAL

FOR %%d IN (google.com ADROOT02.adroot.the-server-company.co.za ) DO (
 NSLOOKUP %%d 2>&1|FIND "Non-existent domain" >nul&IF ERRORLEVEL 1 (ECHO %%d found) ELSE (ECHO %%d NOT found)
)

GOTO :EOF

Yields

google.com found
ADROOT02.adroot.the-server-company.co.za NOT found

for me.

CodePudding user response:

With guidance from this forum I was able to put a command together that outputs the IP address from nslookup or error if no IP found:

FOR /F "usebackq tokens=1* delims=: " %a IN (`^"nslookup server-company.co.za 2^>^&1` ^| findstr ^/N ^/C^:^"Address^" 2^>^&1 ^"`) DO IF %a GTR 3 ( SET res2=%b & echo %res2:~10%) ELSE (echo ERROR)

CodePudding user response:

If the skip=3 is unnecessary this should work:~

nslookup ADROOT02.adroot.the-server-company.co.za | findstr /c:"Address">NUL && echo found || echo not found

Otherwise, not sure.

By the nature of nslookup, I'm assuming the skip=3 is necessary.

It's a bit messy, bit if you have access to PowerShell, this should work:

POWERSHELL -NoP -C "nslookup ADROOT02.adroot.the-server-company.co.za | select -Skip 3 | FINDSTR 'Address'">NUL 2>&1 && ECHO found || echo not found


To explain why the behavior you see is happening, it's likely due to the usage of skip=3. For example, if I run nslookup ;jlkaf93932r923r.com, and I get the result of:

Server:  UnKnown
Address:  192.168.1.1

*** UnKnown can't find ;jlkaf93932r923r.com: Server failed

Then those three lines with text will be skipped, and there will be essentially no output, meaning none of this: @echo %a | findstr /C:"Address" >nul 2>&1 && echo found || echo not found gets executed at all. However, if there were 4 lines, there would be some output, and the DO commands would be run.

  • Related