Have you ever wondered how to get the DNS domain of the machine from a Windows batch file? Well, I needed it and after some investigation I found the USERDNSDOMAIN environment variable and I was happy.

echo %USERDNSDOMAIN%

Until yesterday, when I found out that if the batch file is executed under some of the local machine user accounts (e.g. local Administrator), USERDNSDOMAIN is empty.

I’ve almost started writing WSH script to make it work but at the end I came up with the two lines below. They work regardless of the user account you are running under.

for /F "tokens=2 delims=:" %%i in ('"ipconfig | findstr DNS"') do set TEMP_DOMAIN_NAME=%%i
set FULL_DOMAIN_NAME=%TEMP_DOMAIN_NAME: =%

You will need to have the command extensions enabled to use this script.