path to hosts file from script

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
lazna
Posts: 53
Joined: 27 Dec 2012 10:54

path to hosts file from script

#1 Post by lazna » 15 Mar 2024 04:31

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?

Squashman
Expert
Posts: 4470
Joined: 23 Dec 2011 13:59

Re: path to hosts file from script

#2 Post by Squashman » 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"

ohenryx2
Posts: 5
Joined: 08 Apr 2023 14:16

Re: path to hosts file from script

#3 Post by ohenryx2 » 15 Mar 2024 12:48

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?

lazna
Posts: 53
Joined: 27 Dec 2012 10:54

Re: path to hosts file from script

#4 Post by lazna » 16 Mar 2024 02:29

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.

Post Reply