Update hosts file with VBS (Windows)
Q. I have some hosts that for some reason don't work with the DNS entries. Can I update hosts files on all machines automatically?
A. Ideally, you should fix the DNS, however, this is a quickfix and a show of VBS power in MS world. You can use the following script to achieve this.
This has been tested with Windows XP and Windows 7. You need Administrator rights for this to work. As a note, there's a part of the script that checks to see if the hosts file is read-only. If it is, it makes it writeable.
Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell=CreateObject("WScript.Shell")
WinDir =WshShell.ExpandEnvironmentStrings("%WinDir%")
HostsFile = WinDir & "\System32\Drivers\etc\Hosts"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(HostsFile, ForReading)
Do Until objFile.AtEndOfStream
If InStr (objFile.ReadLine, "10.10.10.105") <> 0 Then
WScript.Quit
End If
i = i + 1
Loop
objFile.Close
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(HostsFile)
If objFile.Attributes AND ReadOnly Then
objFile.Attributes = objFile.Attributes XOR ReadOnly
End If
Set filetxt = fso.OpenTextFile(HostsFile, ForAppending, True)
filetxt.WriteLine(vbNewLine & "10.10.10.105 intranet.corp www.intranet.corp intranet www.intranet")
filetxt.Close
WScript.quit
What does the script do?
Using VBS, it does the following:
- Sets up the variables and specifies where the host file is
- Opens the host file for reading, looks to see if there is an IP entry in it already (ie. 10.10.10.105). We don't want it to append a new entry every time it runs. If it finds the entry, the script exits
- Next, lets see if the file is read only. If it is mark is as read/write (once again, need to be an administrator to do this)
- Finally, open the file and append the required host info at the bottom
- Close and exit
Feel free to modify or use it.
Thanks
DedicatedHosting4u.com
https://winhelp2002.mvps.org/hosts.txt
Purpose is to block all domains listed on TXT file on localhost.
Anyone has an idea?
can it be that
I tried this my self the only problem was that it has no extension like .txt I need that to work
I wanted to block fb on a friends PC and after a minete unblock it :p
I'm not sure what do you mean by modifying the IP instead of a hostname.
If you are doing a search by hostname, just replace it in the script (eg: replace 10.10.10.105 with whatever your hostname is)
This particular script is adding a new host to the list, if it doesn't exist. I'll add another script (later) that will replace a string.