Hosts file scripting

crisp82

Golden Member
Apr 8, 2002
1,920
0
0
Hi,

I am looking to create a batch file or script that will edit the Hosts file by adding entires to the 'localhost' section. It will need to be able to search the file to find out if there are existing entries (ie...the script has already been run) and either replace them or move them down.

Then it will need to save and close.

I am a newbie in the world of scripting. Anyone want to point me in the right direction?
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
I will give you a start. check http://msdn.microsoft.com/scripting/ to see why this works ( or maybe doesn't work, as I wrote it from memory)

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

'open the file and read all of the contents
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\WINDOWS\system32\drivers\etc\hosts", ForReading)
strText = objFile.ReadAll
objFile.Close

'if the hostname is not in the file then add it
If Instr(strText, "hostname") > -1 Then
Set objFile = objFSO.OpenTextFile("C:\WINDOWS\system32\drivers\etc\hosts", ForAppending)
objFile.WriteLine "hostname 192.168.0.1"
objFile.Close
End if
 

nweaver

Diamond Member
Jan 21, 2001
6,813
1
0
I would suggest perl, and have it add a top line that reads something like ##Hosts file edited by Script $scriptver on $date##

then you can parse data and fix stuff easy. SHould be able to load each line into an array, split the array at the spaces and then rebuild/parse each entry.