VB Script : Remove an entry from Hosts File


On Error Resume Next

Set wshshell = createobject("wscript.shell")

Line1="   TEST"
Call RemoveValues(Line1)



Sub RemoveValues(Line)
    Dim varFile         ‘Variable to store the values of the file
    Dim varFileLines    ‘Variable to store the current line read from the file
    Dim WshShell        ‘Object pointing to the WScript
    ‘Initializing the WScript object
    Set WshShell = CreateObject("WScript.shell")
    ‘System root
    SysRoot = WshShell.ExpandEnvironmentStrings("%SystemRoot%")
    ‘File Path
    sFileName = SysRoot & "\system32\drivers\etc\Hosts"
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(sFileName, 1)
    ‘looping through the Hostss file
    Do Until objFile.AtEndOfStream
        ‘Reading a line from the Hosts file
        varFileLines = objFile.ReadLine
        ‘Checking for the search string
        If Trim(varFileLines) <> Line Then
            ‘Building the string without the search string
            If Trim(varFile) = "" Then
                varFile = Trim(varFileLines)
                varFile = varFile & vbCrLf & Trim(varFileLines)
            End If
        End If
    ‘Closing the file object
    Set objFile = Nothing
    ‘Creating the file without the search string
    Set objFile = objFSO.CreateTextFile(sFileName, True, False)
    ‘Writing the lines into the file
    objFile.WriteLine varFile
    ‘Closing the file object
    Set objFile = Nothing
End Sub


2 Responses to “VB Script : Remove an entry from Hosts File”

  1. 1 Piyush Nasa September 27, 2011 at 6:05 am

    Thanks, you saved me lots of time..

  2. 2 renold November 23, 2012 at 9:11 pm

    hi the above script is not working in winows xp. Please help me on this. thanks

    Renold Robin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: