本文給大家分享的是使用VBS實(shí)現(xiàn)刪除host文件里面的指定內(nèi)容,非常的簡單實(shí)用,有需要的小伙伴可以參考下。
要求:原先host里面已增加以下3行
202.102.101.105 intranet.corp
202.102.101.107 mail.intranet.corp
202.102.101.108 sip.intranet.corp
之后不需要此3行內(nèi)容,所以運(yùn)行以上vbs代碼,來刪除host文件此3行
'該腳本要求執(zhí)行用戶有本地管理員權(quán)限
Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell=CreateObject("WScript.Shell")
'WinDir 為windows安裝目錄
WinDir =WshShell.ExpandEnvironmentStrings("%WinDir%")
'設(shè)定host 文件目錄
HostsFile = WinDir & "\System32\Drivers\etc\Hosts"
'檢查host文件是否為只讀,如為只讀,則修改文件屬性
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(HostsFile)
If objFile.Attributes And ReadOnly Then
objFile.Attributes = objFile.Attributes Xor ReadOnly
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(HostsFile, ForReading,true)
'檢查host文件里面是否已經(jīng)更改過了,如果更改過,則不再執(zhí)行腳本
hostfileline=""
Do Until objFile.AtEndOfStream
strline = objfile.ReadLine
If InStr (strline, "202.102.101.105") <> 0 Or (InStr (strline, "202.102.101.107"))<>0 Or (InStr (strline, "202.102.101.108")) Then
strline=""
End If
hostfileline=hostfileline+vbCrLf+strline
Loop
WScript.Echo hostfileline
objFile.Close
'修改host文件
Set filetxt = fso.OpenTextFile(HostsFile, ForWriting )
filetxt.Write hostfileline
filetxt.Close
WScript.Quit