Reputation: 959
I have a program where I take a list of IPs, run nslookup on them, and then store them into two different files, one where the IP is included, one which just has the output of nslookup. To cut my calls to nslookup in half, I would like to call it once, store it in a variable, and then write to both files. But, a simple store doesn't work.
set val=nslookup %ip%
displays
nslookup 127.0.0.1
and not the result of running it.
I've found one way to do this this is
nslookup %ip% | find "Name"> tempFile
set /P result=<tempFile
but I'm now writing to a file and then getting the value back. For that cost, I might as well call nslookup twice. It also requires me to pick a single line (which is fine for me this time, but for other cases it may not work).
I've also tried using the for loop trick
for /f "delims=" %%a in ('nslookup %ip% ^| find "Name"') do set name=%%a
but this only returns the very last line or the one line I specify with find. Still better than the previous example as there are no temp files, but still imperfect.
So my question is if there is some better way to store the return value from a command to a variable.
Edit: Consider
nslookup 127.0.0.1
which returns
Server: fake.com
Address: 0.0.0.0
Name: localhost
Address: 127.0.0.1
Right now, all I want is the name, so returning a single line works for my current batch file. But what if I also needed to know the server, so I want
for /f "delims=" %%a in ('nslookup 127.0.0.1') do set returnVal=%%a
echo %returnVal%
to display
Server: fake.com
Address: 0.0.0.0
Name: localhost
Address: 127.0.0.1
where right now it only displays
Address: 127.0.0.1
Upvotes: 0
Views: 3450
Reputation: 67256
The Batch file below store the four non-empty lines shown by nslookup in an array with four elements:
@echo off
setlocal EnableDelayedExpansion
set n=0
for /f "delims=" %%a in ('nslookup 127.0.0.1') do (
set /A n+=1
set returnVal[!n!]=%%a
)
rem To show all non-empty lines:
for /L %%i in (1,1,%n%) do echo !returnVal[%%i]!
rem Or:
echo Line with Name: %returnVal[3]%
Upvotes: 1
Reputation: 7105
Try:
@echo off
setlocal
for /f "usebackq tokens=1,2 delims=:" %%a in (`nslookup %ip%`) do echo %%a:%%b
Upvotes: 0