Using Windows Batch File to replace Hosts file


I currently have a logon script that is set to replace the local machine Hosts file with that of a modified hosts file.

The problem that I am running into is that the original hosts file on the local machine is read-only, so the file is not copied over. I figured that out after removing the read-only access and then running my script again.

I am looking for the code snippet to remove the "read-only" permission before the script attempts to copy the file.

Can anyone show what the line of code I need for this?
copy "\\server\share\Hosts\*.*" "%systemroot%\system32\drivers\etc\" /Y

Open in new window

Who is Participating?
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
When you use attrib, then copy, you should reset the r/o flag, so HOSTS is write-protected again:

attrib -r "%systemroot%\system32\drivers\etc\hosts"
copy "\\server\share\Hosts\*.*" "%systemroot%\system32\drivers\etc\" /Y
attrib +r "%systemroot%\system32\drivers\etc\hosts"
xcopy can do that in one go, if the source file is r/o:
xcopy /R /Y /D /K \\server\share\Hosts\*.*"  "%systemroot%\system32\drivers\etc\"
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
You can use xcopy instead, with option /R:

xcopy /R /Y /D \\server\share\Hosts\*.*" "%systemroot%\system32\drivers\etc\"
Option /D can be omitted, it will copy only files newer than the destination.
Is there entries already in the hosts file apart from default entry?
Christopher McKayMicrosoft Network AdministratorCommented:
the command you're looking for in your script is the attrib command. Add this to your script:

attrib -r %%systemroot%\system32\drivers\etc\hosts"

Hope this helps!


id4382Author Commented:
The commands given by Qlemo worked successfully.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.