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