Geoffrey DeFilippi

VBScript - Modify the Hosts file

August 20, 2007 @ 9:18 am by Geoff | Programming, Tools

Here is a sample VBScript that add / deletes an entry from a hosts file.  If you aren’t aware the host file will force a domain name to resolve to a set IP address without a DNS lookup.

result = MsgBox("Add or remove (site.example.com) from your Host file?", 
    vbYesNo + vbQuestion, "Input Required")
 
Const ForReading = 1 ' Open file read only
Const ForWriting = 2 ' Open file read write
 
Dim objFso, objFile, strFileName, strText, strNewText
 
' It might be nice at some point to get this via the environment variables
strFileName = "C:\windows\system32\drivers\etc\hosts" 
 
Set objFso = CreateObject("Scripting.FileSystemObject")
 
' Open the File and read into string
Set objFile = objFso.OpenTextFile(strFileName, ForReading) 
strText = objFile.ReadAll 
objFile.Close ' close the file
 
' Create a regular expression
Dim re
Set re = New RegExp 
re.Pattern = ".*site\.example\.com.*\n" 
re.IgnoreCase = True
re.Global = True
 
' Remove the entry if found
strNewText = re.Replace(strText, "") 
 
'  If user requests add entry
If result = vbYes Then
    strNewText = strNewText + "172.16.1.1 site.example.com" 
End If
 
' Write out file (deletes old file)
Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 
objFile.WriteLine strNewText ' Write out the string contents
objFile.Close
 
' Flush the DNS Cache so change will take effect
Set WshShell = CreateObject("WScript.Shell") 
WshShell.Run "ipconfig /flushdns"

File Scripting credit to:
How Can I Read a Text File on a Remote Computer?

Happy Coding

1 Response to “VBScript - Modify the Hosts file”

  1. February 6th, 2008 @ 2:45 pm by Microsoft Quick Tips » Blog Archive » VBScript to modify a Hosts file entry:

    [...] Go here for an excellent script to allow you to modify, remove or add an entry in your hosts file. This is particularly useful when you have many to change. [...]

Leave a comment