Hi Everyone,


I have to add some host entries in Hosts file through vbscript. I have the script which checks for the host entry, if found missing then it add it in Hosts file. But before adding those host entries, I need to insert a blank line so there is atleat one space between the old and new host entries...


My old script is which need to be modified but I'm not sure how to do that:

'Function Name  : Insert mutiple Values in Host file With Check
'Purpose        : To add the a seleted line in the file

Dim varLine    'Variable to store the current value to be written

'Defining the value of each line to be searched and written
call InsertValues(varLine)

'InsertValues function will search value passed as varibale and if not found it will write this variable at end of file.
Sub InsertValues(varLine)

Dim varFileLines    'Variable to store the curretly read line
Dim sFlag           'Varaiable to store the flag value
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)

sFlag = "False" 'Assumption the search string is not found

'looping through the services file
Do Until objFile.AtEndOfStream
    varFileLines = objFile.ReadLine
    If Trim(varFileLines) = varLine Then
        sFlag = "True"  'Search string is found
        Exit Do         'Quiting the loop
    End If

'Closing the object
Set objFile = Nothing

'Checking for the flag
If Trim(sFlag) = "False" Then
    'Writing the line since the search string is not found in the file
    Set objFile = objFSO.OpenTextFile(sFileName, 8)
    objFile.WriteLine varLine
End If

Set objFile = Nothing

End Sub


0 Comments   [ - ] Hide Comments


Please log in to comment

Answer this question or Comment on this question for clarity




There are many ways to obtain what you want and a lot of ways to optimize the Sub (for example move away the file opening and closing all the time that the function is invoked)


The simplest and harmless thing to do without the need to play a lot with the script is to open the host file and add a newline regardless before to invoke the function one or more times.


A newline more or less in the file will not harm and you avoid doing a lot of reworking in the script.






Answered 01/17/2013 by: StockTrader
Red Belt

Please log in to comment

see if the info in this link helps


Answered 01/16/2013 by: SMal.tmcc
Red Belt

  • This content is currently hidden from public view.
    Reason: Removed by member request
    For more information, visit our FAQ's.
Please log in to comment