Pages

Friday 6 July 2012

Append Entry in Hosts file - VBScript



Following script will append the entry present in sample.txt file to hosts file. 


Following script needs sample.txt and hosts file to be present in the same directory where script file is locatied. Please change TargetFile and Input paths according to requirement.


************************************************************

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim TargetFile,objWshShell,objFSO, Input, ProgramFiles, WinDir
Dim objTextFile, Target


Set objWshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")


ProgramFiles = ObjWshShell.ExpandEnvironmentStrings("%ProgramFiles%")
WinDir = ObjWshShell.ExpandEnvironmentStrings("%WinDir%")


CDir = objFSO.GetParentFolderName(Wscript.ScriptFullName)


Set Targetfile = objFSO.GetFile(CDir & "\hosts")
Set Input = objFSO.GetFile(CDir & "\Sample.txt")


Set objTextFile = objFSO.OpenTextFile (Input, ForReading)
Set Target = CreateObject("Scripting.FileSystemObject")
Set TargetFile = Target.OpenTextFile (TargetFile, ForAppending, True)


Do Until objTextFile.AtEndOfStream
Input = objTextFile.ReadLine
TargetFile.WriteLine(Input)
Loop


TargetFile.Close
ObjTextFile.Close


***************************************************************


-> Create sample.txt file with following content for example and save it in same location where vbscript file is present.

                  #     10.10.10.10    www.sample.com


-> Place hosts file in the same location where VBscript is present.
-> Run the VBscript, above line will be appended to hosts file.





No comments:

Post a Comment