0

I have the code below that returns the hostname and IP address of a given server. How can i only have the hostname as the output?

FOR /F %%i in (servers.txt) do FOR /F "skip=3 delims=: tokens=2 usebackq" %%j in (`nslookup %%i`) do @echo %%j >> Devices_With_IP.txt

2 Answers 2

1

Assuming your machine uses English:

FOR /F %%i in (servers.txt) do FOR /F "delims=: tokens=2" %%j in (
  'nslookup %%i ^| find "Name:"'
) do @echo %%j >> Devices_With_IP.txt
Sign up to request clarification or add additional context in comments.

Comments

1

Try using the findstr command on the output of your nslookup to get only the line containing "Name".

FOR /F %%i in (servers.txt) do FOR /F "tokens=2 usebackq delims=: " %%j in (`nslookup %%i ^| findstr Name`) do @echo %%j >> Devices_With_IP.txt

Note that I also rearranged the /F conditions in the second loop in order to include space as a deliminator, this removes the leading spaces before the output.

Using the find command instead of findstr -

FOR /F %%i in (servers.txt) do FOR /F "tokens=2 usebackq delims=: " %%j in (`nslookup %%i ^| find "Name"`) do @echo %%j >> Devices_With_IP.txt

Just realized that using find instead of findstr makes this (almost) exactly the same as dbenham's answer.

5 Comments

No output is generated.
@PeanutsMonkey, I just added the redirect to your Devices_With_IP.txt, before it only outputted to the terminal. Was that the problem?
Nope. I had it as well. No results are displayed nor is a file generated.
@PeanutsMonkey it works for me. What version of Windows are you running?
I'm running Windows 7. I do have access to the findstr command. Ran it against the dir command and it works just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.