Page 1 of 1

path to hosts file from script

Posted: 15 Mar 2024 04:31
by lazna
trying to read path of hosts file but it does not work in script

Code: Select all

@echo off
for /f "tokens=1,3" %%a in ('
			reg query "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /V "DataBasePath"
			') do (
			if "%%~a"=="DataBasePath" set "hostspath=%%b"
			)
if exist "%hostspath%\hosts" (echo yes) else (echo no)
echo "%hostspath%\hosts"
dir "%hostspath%\hosts"
it output

Code: Select all

no
"%SystemRoot%\System32\drivers\etc\hosts"
The system cannot find the path specified.
but when trying

Code: Select all

dir "%SystemRoot%\System32\drivers\etc\hosts"
on command line, it give me

Code: Select all

Directory of C:\WINDOWS\System32\drivers\etc

23/05/2021  16:13               895 hosts
               1 File(s)            895 bytes
               0 Dir(s)  42,341,171,200 bytes free
what am I doing wrong?

Re: path to hosts file from script

Posted: 15 Mar 2024 12:47
by Squashman
%systemroot% is a variable which means you need double expansion.

Code: Select all

if "%%~a"=="DataBasePath" CALL set "hostspath=%%b"

Re: path to hosts file from script

Posted: 15 Mar 2024 12:48
by ohenryx2
The hosts file on Windows is normally protected. Are you running as admin? Have you tried checking the attributes of the hosts file, is it ReadOnly, Hidden, System?

Re: path to hosts file from script

Posted: 16 Mar 2024 02:29
by lazna
Squashman wrote:
15 Mar 2024 12:47
%systemroot% is a variable which means you need double expansion.

Code: Select all

if "%%~a"=="DataBasePath" CALL set "hostspath=%%b"
Thanks Sqashman, you are right, it does work with call.