简体   繁体   中英

Windows Batch Check Hostname Exists

I want to check if a hostname exists on my PC (ie found in hosts file under C:\\Windows\\System32\\drivers\\etc ).

Is there a way to find if it exist using a batch command or some other way?

Give a try for this batch file with some extra info :

@echo off
set "SearchString=localhost"
set "LogFile=%userprofile%\Desktop\LogFile.txt"
set "hostspath=%windir%\System32\drivers\etc\hosts"
(
    Echo  **************************** General info ****************************
    Echo Running under: %username% on profile: %userprofile%
    Echo Computer name: %computername%
    Echo Operating System:
    wmic os get caption | findstr /v /r /c:"^$" /c:"^Caption"
    Echo Boot Mode:
    wmic COMPUTERSYSTEM GET BootupState | find "boot"
    Echo Antivirus software installed:
    wmic /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get displayName | findstr /v /r /c:"^$" /c:"displayName"
    Echo Executed on: %date% @ %time%
    Echo  ********************* Hosts' File Contents with the string "%SearchString%" ************************
)>"%LogFile%"

for /f "delims=" %%a in ('Type "%hostspath%" ^| find /I "%SearchString%"') Do (
     echo %%a >> "%LogFile%"
)
Start "" "%LogFile%"

Easier and more robust solution

url.bat:

@echo off

set url=%1
ping -n 1 %url% > nul 2> nul
if "%errorlevel%"=="0" (
 echo %url% exists
) else (
 echo %url% does not exist
)

Test

> url.bat google.com
google.com exists

> url.bat google.commmmmm
google.commmmmm does not exist

What you possibly can do is pinging the hostname you are looking for and then check for certain strings, that will show you if the hostname could be found or not. Would look like this (I guess):

@echo off
setlocal EnableDelayedExpansion
set /p input= "Hostname"
set hostexists=yes
For /f "tokens=1,2" %%a in ('ping -n 1 !input!') do (
    if "x%%a"=="xFOO" if "x%%b"=="xBAR" set hostexists=no
)
If "x!hostexists!"=="xno" (
echo. "Does not exist"
) ELSE (
echo. "Does exist"
Pause

Basic thought is that when you try to ping a hostname that is not available, you will get a specific output from the commandline. Try it yourself: Open the cmd.exe (Hit the Windows-Button +R and type cmd ) and in the commandline write ping foobar and wait a bit. You should get a message like: Ping-Request could not find "foobar" [...]. You take the first two words and put them into the code: 1st word to FOO and 2nd to BAR .

The program will look into the output of the ping command and place the first two words (=tokens) in %%a and %%b checking if they are equal to the desired words, marking the host does not exist.

I hope this will help :) Not sure if that is what you wanted :D

Greetings

geisterfurz007

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM