The hosts file in Windows OS is an operating system file that maps hostnames to IP addresses. The hosts file is used to resolve hosts names before DNS, and it can be found in c:\windows\system32\drivers\etc\.
It’s not very popular nowadays for applications to place anything in this file, back in the days this file was massive.
But let’s say you have a specific line in it programmatically using VBScript. To do this, the following steps should be done:
- Open the hosts file
- Parse the file line by line
- Check if the line matches the input text
- If the line matches, delete the line
- Save and close the file
Bellow, the code for the script:
On Error Resume Next Set oWSH = createobject("wscript.shell") Line1="0.0.0.0 TEST" Call RemoveValues(Line1) Sub RemoveValues(Line) Dim varFile Dim varFileLines Dim oWSH Set oWSH = CreateObject("WScript.shell") SysRoot = oWSH.ExpandEnvironmentStrings("%SystemRoot%") sFileName = SysRoot & "\system32\drivers\etc\Hosts" Set oFSO = CreateObject("Scripting.FileSystemObject") Set objFile = oFSO.OpenTextFile(sFileName, 1) Do Until objFile.AtEndOfStream varFileLines = objFile.ReadLine If Trim(varFileLines) <> Line Then If Trim(varFile) = "" Then varFile = Trim(varFileLines) Else varFile = varFile & vbCrLf & Trim(varFileLines) End If End If Loop objFile.Close Set objFile = Nothing Set objFile = oFSO.CreateTextFile(sFileName, True, False) objFile.WriteLine varFile objFile.Close Set objFile = Nothing End Sub
The only thing you need to change is Line1 with the desired text that you want to be deleted. If you want to delete multiple lines, you could do something like this:
Line1="0.0.0.0 TEST" Line2="184.108.40.206 TEST2" Call RemoveValues(Line1) Call RemoveValues(Line2)
Hope that you find this script useful. For any script suggestions leave me an email.