修改";C:\Windows\System32\drivers\etc\hosts";使用VBScript的文件

修改";C:\Windows\System32\drivers\etc\hosts";使用VBScript的文件,vbscript,Vbscript,我想使用VBScript在C:\Windows\System32\drivers\etc\hosts中追加一行。我尝试先使用以下代码读取此文件: Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Windows\System32\drivers\etc\hosts",2,true) file = Split(filestreamIN.ReadAll(), vbCrLf) for i = L

我想使用VBScript在
C:\Windows\System32\drivers\etc\hosts
中追加一行。我尝试先使用以下代码读取此文件:

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
但是我在第二行有个错误:坏文件模式。我使用以下命令运行它:

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

以管理员身份运行
cmd
。任何帮助都会很好。

C:\Windows\System32\drivers\etc
是一个目录。

打开文件进行附加,只需输出所需内容即可。它将自动追加

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
当然,这并不能解决附加文件中已有数据的潜在问题

如果要先读取文件,请打开它进行读取,读取数据,关闭它,然后重新打开它进行附加并进行更改。没有必要打开它进行书写


如果要编辑该文件,请将其读入,关闭,重新打开以进行写入,然后写出编辑后的数据。

这是您需要的bat file inc案例

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"