2
votes

I want to append a line to C:\Windows\System32\drivers\etc\hosts using VBScript. I tried to read this file first using this code:

Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Windows\System32\drivers\etc\hosts",2,true)
file = Split(filestreamIN.ReadAll(), vbCrLf)
for i = LBound(file) to UBound(file)
msgbox file(i)
Next
filestreamIN.Close()
Set filestreamIN = Nothing

But I got an error in the second line: Bad file mode. I ran it using this command:

cscript "D:\Project\AXA\AXADEPROJ-867\add host.vbs"

with cmd being run as an administrator. Any help would be great.

3

3 Answers

0
votes

Open the file for appending, and simply output what you want. It will automatically be appended.

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oHosts = oFSO.GetFile("C:\Windows\System32\drivers\etc\hosts")
WScript.Echo oHosts.attributes
Set fileAPPEND = _
  oFSO.OpenTextFile("C:\Windows\System32\drivers\etc\hosts", 8, true)
fileAPPEND.Write("192.168.0.1 MyMachine")
fileAPPEND.Close()
Set fileAPPEND = Nothing
Set oHosts = Nothing
Set oFSO = Nothing

Of course that does not address a potential issue of appending data that is already in the file.

If you want to read the file first, open it for reading, read the data, close it, then re-open it for appending and make your changes. There is no need to open it for writing.

If you want to edit the file, read it in, close it, reopen it for writing, and write out the edited data.

0
votes

C:\Windows\System32\drivers\etc is a directory.

0
votes

here is the bat file inc case you need

type "%windir%\system32\drivers\etc\hosts" | find /i "WEBSITE1" || echo 10.0.0.0 WEBSITE1 >> "%windir%\system32\drivers\etc\hosts"

type "%windir%\system32\drivers\etc\hosts" | find /i "SERVER1" || echo 10.0.0.0 SERVER1 >> "%windir%\system32\drivers\etc\hosts"