How to Perform a DNS Lookup with NSLOOKUP in Batch Script
Domain Name System (DNS) is the "Phonebook" of the internet, translating human-readable names like google.com into numeric IP addresses. When a web script or a server connection fails, a DNS lookup is the first step in troubleshooting. By using the nslookup command in a Batch script, you can programmatically verify if a domain is resolving correctly, identify which DNS server your machine is using, and even extract specific records like mail servers (MX) or aliases (CNAME).
This guide will explain how to automate and parse DNS lookups.
Method 1: Simple IP Verification
This method checks if a hostname has a valid IP address and displays it.
@echo off
setlocal enabledelayedexpansion
set "Target=google.com"
set "ResultIP="
set "SkipDNS=1"
echo [DNS] Searching for %Target%...
echo.
:: Run nslookup and filter for 'Address' lines
:: The FIRST match is the DNS server itself, so skip it
for /f "tokens=2" %%a in ('nslookup %Target% 2^>nul ^| findstr /i "Address"') do (
if !SkipDNS! equ 1 (
set "SkipDNS=0"
) else (
set "ResultIP=%%a"
)
)
if defined ResultIP (
echo [RESULT] %Target% resolves to: !ResultIP!
) else (
echo [ERROR] Could not resolve %Target%. Check domain name or DNS settings.
)
pause
endlocal
Why we skip the first Address: The raw output of nslookup contains two Address lines. The first one is the IP of your DNS server, not the target. The SkipDNS flag ensures we only capture the actual result.
Method 2: Verifying a Specific Record Type (MX/CNAME)
If you are troubleshooting email issues, you need the "MX" (Mail Exchange) record rather than the standard IP.
@echo off
setlocal
set "Domain=example.com"
echo [AUDIT] Fetching Mail Servers (MX) for %Domain%...
echo.
:: Flush cached records so we get a live result
ipconfig /flushdns >nul 2>&1
:: Set type to MX and query the domain
nslookup -type=mx %Domain% 2>nul
:: Check for lookup failure in the output
nslookup -type=mx %Domain% 2>nul | findstr /i "can't.find NXDOMAIN" >nul 2>&1
if %errorlevel% equ 0 (
echo.
echo [ERROR] No MX records found. Domain may not exist or has no mail servers.
)
pause
endlocal
Method 3: Testing a Specific DNS Server
Sometimes your local DNS is "lying" or outdated (DNS poisoning). You can force nslookup to ask a specific public server like Google (8.8.8.8) or Cloudflare (1.1.1.1).
nslookup on Windows returns errorlevel 1 for non-authoritative answers, which is the normal, successful response for any public domain. You cannot rely on %errorlevel% alone. Instead, parse the actual output for known failure strings.
@echo off
setlocal
set "Target=myinternal.site"
set "CustomDNS=8.8.8.8"
set "TempFile=%TEMP%\nslookup_result.tmp"
echo [TEST] Querying %CustomDNS% for %Target%...
echo.
:: Capture all output to a temp file for reliable parsing
nslookup %Target% %CustomDNS% > "%TempFile%" 2>&1
:: Display the raw result
type "%TempFile%"
echo.
:: Check for failure indicators in the output
:: (nslookup's errorlevel is UNRELIABLE, as it returns 1 even on success)
findstr /i "can't.find NXDOMAIN refused timed.out" "%TempFile%" >nul 2>&1
if %errorlevel% equ 0 (
echo [WARN] Public DNS cannot find this domain or the query failed.
) else (
echo [OK] Query completed successfully.
)
:: Clean up
del "%TempFile%" >nul 2>&1
pause
endlocal
How to Avoid Common Errors
Wrong Way: Parsing "Non-authoritative answer"
The nslookup output contains human-readable headers like "Non-authoritative answer." If your script simply "captures the first line," you will get useless information.
Correct Way: Use findstr or a FOR loop to target the second Address: result, which is the actual target IP. Use a skip flag or counter to ignore the first match (the DNS server's own address).
Wrong Way: Relying on %errorlevel%
nslookup returns errorlevel 1 for non-authoritative answers, which is the standard response for any public domain lookup. A script that checks if %errorlevel% neq 0 will falsely report failures on perfectly valid queries.
Correct Way: Redirect the output to a temp file or pipe it through findstr, and check for actual failure strings like can't find, NXDOMAIN, refused, or timed out.
Problem: Multiple IP Addresses
A large site (like Amazon or Google) has many IP addresses. nslookup will return a list.
Solution: If you need all of them, don't use a simple set variable. Redirect the output to a text file for complete analysis.
nslookup google.com 2>nul | findstr /i "Address" > "%TEMP%\all_ips.txt"
Best Practices and Rules
1. Identify "NXDOMAIN"
If nslookup returns "Non-existent domain," it means the domain literally doesn't exist in the global registry. This is common if you have a typo in your script.
2. DNS Cache Issues
If your script is getting an "old" IP after you just changed a domain setting, remember that Windows caches these results. Use ipconfig /flushdns in your script before performing the lookup for live troubleshooting.
ipconfig /flushdns >nul 2>&1
3. Check for Aliases (CNAME)
Sometimes a domain isn't an IP; it's a "CNAME" that points to another domain (e.g., www.site.com → site.github.io). Use -type=cname to see the chain of resolution.
4. Always Use setlocal / endlocal
Without setlocal, every variable your script creates leaks into the parent shell session. This can cause conflicts when running multiple scripts in sequence.
Conclusions
Performing DNS lookups with nslookup is a foundational skill for automated networking. By bridging your Batch script with DNS queries, you gain the ability to verify infrastructure routing, troubleshoot connectivity in real-time, and ensure your scripts are targeting the correct, live IP addresses. This visibility is essential for maintaining reliable connections between your servers and services in a dynamic internet environment.