Kae Travis

Use VBScript to amend the the Hosts/Services or any other text file

Description:

This post shows how to use VBScript to amend the the Hosts/Services or any other text file. It contains two scripts to add/remove lines of text. This example adds to the C:\Windows\System32\drivers\etc\Services file.

Source:

N/A

Script:

Add to Services file

dim objFSO : set objFSO = CreateObject("Scripting.FileSystemObject")
dim windowsFolder: windowsFolder = objFSO.GetSpecialFolder(0)
dim targetFile : targetFile = windowsFolder & "\System32\drivers\etc\Services"
Dim arrobjFileLines()
dim i : i = 0
Const ForAppending = 8
Const ForReading = 1
if objFSO.FileExists(targetFile) Then
Dim objFile : Set objFile = objFSO.OpenTextFile(targetFile, ForReading)
strobjFile = objFile.ReadAll
objFile.Close
Set objFile = Nothing
Set objFile = objFSO.OpenTextFile(targetFile, ForAppending)
if right(strobjFile,2) <> VbCrlf then
objFile.WriteBlankLines 1
end if
objFile.WriteLine "alkaneTest1 3601/tcp"
objFile.WriteLine "alkaneTest2 3602/tcp"
objFile.WriteLine "alkaneTest3 3603/tcp"
objFile.close
Set objFile = Nothing
end if
Set objFSO = Nothing

Remove from Services file

dim objFSO : set objFSO = CreateObject("Scripting.FileSystemObject")
dim windowsFolder: windowsFolder = objFSO.GetSpecialFolder(0)
dim filename: filename = windowsFolder & "\System32\drivers\etc\Services"
Const ForReading = 1
Const ForWriting = 2
if objFSO.FileExists(filename) Then
Set objFile = objFSO.OpenTextFile(filename, ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If strLine <> "alkaneTest1 3601/tcp" _
AND strLine <> "alkaneTest2 3602/tcp" _
AND strLine <> "alkaneTest3 3603/tcp" Then
strNewContents = strNewContents & strLine & vbCrLf
End If		
Loop
objFile.Close
Set objFile = Nothing
Set objFile = objFSO.OpenTextFile(filename, ForWriting)
objFile.Write strNewContents
objFile.Close
Set objFile = Nothing
end if
Set objFSO = Nothing

 

Use VBScript to amend the the Hosts/Services or any other text file
Use VBScript to amend the the Hosts/Services or any other text file

Leave a Reply