Hi,

Is there a way using script to eddit host file? What I need to do is change:

#     127.0.0.1       localhost

to

     127.0.0.1       localhost (without hash)

Is it possible, i just find for now script which is changing everything, but that is not what I need. Please help or give some advice.

Thank you!

Answer Summary:
See dandirk's answer
Cancel
0 Comments   [ + ] Show Comments

Comments

Please log in to comment

Community Chosen Answer

2

What about this, how can I change hard coded entries becasue if it stays like that it workes:

On Error Resume Next

Set objFSO = CreateObject("Scripting.FileSystemObject")

'Sets variables
FilePath="c:\windows\system32\drivers\etc\hosts"
SearchTerm="# 127.0.0.1       localhost"
NewText=" 127.0.0.1       localhost"

'Opens text file in read mode (Read=1, Write=2, Append=8)
Set objFile = objFSO.OpenTextFile(FilePath, 1)

'Adds all text in text file to "FileContent" string
FileContent = objFile.ReadAll
objFile.Close

'Instr searches "FileContent" looking for "SearchTerm", if not found returns 0
if Instr(FileContent,SearchTerm) = 0 then
  
   'Not found code
   'Opens text file in append mode so you can add text (Read=1, Write=2, Append=8)
   Set objFile = objFSO.OpenTextFile(FilePath, 8)
   'Writes new line to text fle vbCrLf inserts a return(s) to ensure new line
   objFile.WriteLine (vbCrLf & NewText & vbCrLf)
   objFile.Close

Else
  
   'Found search term
   ReplaceOldLine = Replace(FileContent, "# 127.0.0.1       localhost", NewText)
   'Opens text file in write mode to replace old line (Read=1, Write=2, Append=8)
   Set objFile = objFSO.OpenTextFile(FilePath, 2)
   're-writes whole content of file with replaced values (if needed)
   objFile.WriteLine ReplaceOldLine
   objFile.Close

end If

WScript.Quit

Answered 08/10/2012 by: lanselots
Fourth Degree Brown Belt

Please log in to comment

Answers

1

Here is a VBS that worked for me when I had to either add or replace an entry.  Later (second script) I created a slightly better script that finds and deletes whole lines instead of having to match specific line of text exactly.  You could modify this script to find the line and replace as well.  Both should work.

 On Error Resume Next

Set objFSO = CreateObject("Scripting.FileSystemObject")

'Sets variables
FilePath="c:\windows\system32\drivers\etc\hosts"
SearchTerm="TEXT to find in file"
NewText="New TEXT you want to add/replace"

'Opens text file in read mode (Read=1, Write=2, Append=8)
Set objFile = objFSO.OpenTextFile(FilePath, 1)

'Adds all text in text file to "FileContent" string
FileContent = objFile.ReadAll
objFile.Close

'Instr searches "FileContent" looking for "SearchTerm", if not found returns 0
if Instr(FileContent,SearchTerm) = 0 then
   
   'Not found code
   'Opens text file in append mode so you can add text (Read=1, Write=2, Append=8)
   Set objFile = objFSO.OpenTextFile(FilePath, 8)
   'Writes new line to text fle vbCrLf inserts a return(s) to ensure new line
   objFile.WriteLine (vbCrLf & NewText & vbCrLf)
   objFile.Close

Else
   
   'Found search term
   ReplaceOldLine = Replace(FileContent, "LINE/Text to replace", NewText)
   'Opens text file in write mode to replace old line (Read=1, Write=2, Append=8)
   Set objFile = objFSO.OpenTextFile(FilePath, 2)
   're-writes whole content of file with replaced values (if needed)
   objFile.WriteLine ReplaceOldLine
   objFile.Close

end If

WScript.Quit
 
 
 
 'This script finds text in a file and removes the WHOLE line if found.


OnErrorResumeNext

'Set variables
strTextFilePath="c:\windows\system32\drivers\etc\hosts"
strSearchTerm="TEXT to search"


''''''''''''''''''''''''''''''''''''''''''''''''''
'This section opens the file searches for the strSearchTerm, and shuts script down if not in doc.  If exists it continues to remove lines.  This is to avoid re-writting file when not needed,
'Opens text file in read mode (Read=1, Write=2, Append=8)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strTextFilePath, 1)

'Adds all text in text file to "FileContent" string
FileContent = objFile.ReadAll
objFile.Close

'Instr searches "FileContent" looking for "SearchTerm", if not found returns 0 and closes script.
ifInstr(FileContent,strSearchTerm) = 0then
   
    objFile.Close
    wscript.Quit
    
endIf
'''''''''''''''''''''''''''''''''''''''''''''''''''

'Opens text file in read mode (Read=1, Write=2, Append=8)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strTextFilePath, 1)

'Loop through text file line by line, if NOT equal to strSearchTerm line is added to strNewContents (which is later written to text file).  Thus any line that matches strSearchTerm is omitted and not written (or removed).
DoUntil objFile.AtEndOfStream
    strLine = objFile.ReadLine
    IfInStr(strLine, strSearchTerm) = 0Then
        strNewContents = strNewContents & strLine & vbCrLf
    EndIf
Loop
objFile.Close

'Opens text file in write mode (Read=1, Write=2, Append=8)
Set objFile = objFSO.OpenTextFile(strTextFilePath, 2)

'Writes content of strNewContents to file, which should be missing lines that contain the strSearchTerm.
objFile.Write strNewContents
objFile.Close

Answered 08/02/2012 by: dandirk
Third Degree Green Belt

  • But how can you replace hard coded entries in it, as I did but not working, working only if I leave as is but that is not acceptable.
    • This content is currently hidden from public view.
      Reason: Member has been banned from the site
      For more information, visit our FAQ's.
Please log in to comment
This content is currently hidden from public view.
Reason: Removed by user request
For more information, visit our FAQ's.

0

I belive that is not the best practice to do that, that is why I need just remove hash when installing and after uninstalling app put it back.

Answered 08/02/2012 by: lanselots
Fourth Degree Brown Belt

  • I would just append a new line at the end and do not worry about the one with the #

    echo 127.0.0.1 localhost >> %SYSTEMDRIVE%\Windows\System32\Drivers\Etc\Hosts
  • 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
0

here is a find and replace script (case insensitive)

[cscript|wscript] replace.vbs Find Replacewith File

Find … Required. Substring being searched for.
Replacewith … Required. Replacement substring.
File … Source and destination file for the replacement

 

Dim FileName, Find, ReplaceWith, FileContents, dFileContents
Find         = WScript.Arguments(0)
ReplaceWith  = WScript.Arguments(1)
FileName     = WScript.Arguments(2)

'Read source text file FileContents = GetFile(FileName)

'replace all string In the source file dFileContents = replace(FileContents, Find, ReplaceWith, 1, -1, 1)

'Compare source And result if dFileContents <> FileContents Then
  'write result If different   WriteFile FileName, dFileContents

  Wscript.Echo "Replace done."
  If Len(ReplaceWith) <> Len(Find) Then 'Can we count n of replacements?     Wscript.Echo _
    ( (Len(dFileContents) - Len(FileContents)) / (Len(ReplaceWith)-Len(Find)) ) & _
    " replacements."
  End If
Else
  Wscript.Echo "Searched string Not In the source file"
End If

'Read text file function GetFile(FileName)
  If FileName<>"" Then
    Dim FS, FileStream
    Set FS = CreateObject("Scripting.FileSystemObject")
      on error resume Next
      Set FileStream = FS.OpenTextFile(FileName)
      GetFile = FileStream.ReadAll
  End If
End Function

'Write string As a text file. function WriteFile(FileName, Contents)
  Dim OutStream, FS

  on error resume Next
  Set FS = CreateObject("Scripting.FileSystemObject")
    Set OutStream = FS.OpenTextFile(FileName, 2, True)
    OutStream.Write Contents
End Function

 

Answered 08/02/2012 by: SMal.tmcc
Red Belt

  • I thought you would need something like this so you can also change it back when done
    • SMal.tmcc,
      How do I write the line that calls the vbs using the arguments?

      I'm lost in over-thinking this.

      We're doing a failover test tomorrow (Sat. morning) and I want our testers to be able to swap the host entries out and store their existing hosts file content to be returned after the testing. Some hosts files may differ from others so I can't blanket plaster the same hosts data back to them all at the end.

      I'm a little confused with what the arguments should be. I can figure it out on my own, but I may not have time before tomorrow.

      I'm not sure what the "Replacewith" or the "Find" should be. I have 2 lines to add. Examples below. I don't understand how to put 2 lines of a host file into the command line as the Replacewith string.

      What am I finding?
      I have host files that are the basic default and some with one or two lines of existing entries that need to be written back to the hosts file after testing.

      wscript hostreplace.vbs [txt file with the changes??]

      Ex.
      Source host file is the default windows host file with one extra line say. The data to go into it is like below.
      These sample IP's and names are what I need in ou host files during testing.
      192.168.1.110 Svrgen1 Svrgen1-cifs BBia1tst1 BBia1tst1-cifs BBia19Atst1
      192.168.1.120 Svrgen2 Svrgen2-cifs BBia2tst1 BBia2tst1-cifs BBia29Atst1

      After testing, I need to revert all the host files back to what each was prior to testing.

      Note: Yes, those are fake IP's and names.
      • I'm not sure how anyone else has done it, but the only way I'm able to edit the Win 7 hosts file is to grant my account full access to it. Even though I'm logged on as a domain admin in the local administrators group. It still wanted me to specifically grant FULL access on the hosts file to my admin account.

        I guess the scripts go out the window on this one. Too bad. Was hoping to save some time tomorrow.
Please log in to comment
0

If you just want to add entries then you can use this script

 

On Error Resume Next

Dim IPAddress, HostName, Line

IPAddress="192.168.1.1"
HostName="MYCOMPUTERNAME"

Line=IPAddress & "       "  & HostName

Call AddValues(Line)

 

Sub AddValues(Line)
    Dim varFile
    Dim varFileLines
    Dim WshShell
    Dim WinDir, objFSO, objFile, Flag
  
    Set WshShell = CreateObject("WScript.shell")

    WinDir = WshShell.ExpandEnvironmentStrings("%WinDir%")
    sFileName = WinDir & "\system32\drivers\etc\Hosts"
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(sFileName,1)

    Flag=0
   

    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
    Else
        Flag=1
        End If
    Loop


        objFile.Close

    If Flag=0 then

        varFile = varFile & vbCrLf & Line
 
        Set objFile = objFSO.CreateTextFile(sFileName, True, False)
    
        objFile.WriteLine varFile

    objFile.Close
    End if
    Set objFile = Nothing
    Set objFSO = Nothing
    Set WshShell = Nothing

End Sub

 

Answered 08/02/2012 by: jagadeish
Red Belt

Please log in to comment
0

Thank you "dandrink" your script was really helpfull and it worked like sharm :)

Answered 08/02/2012 by: lanselots
Fourth Degree Brown 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
0

Hi, How can I replace in dandrink script hard coded pass?

Answered 08/15/2012 by: lanselots
Fourth Degree Brown Belt

Please log in to comment
Answer this question or Comment on this question for clarity