Search code examples
arraysstringvbscript

Adding and Exporting strings in array with VBS script


I am working on a VBS script that will ask the user to type in the address of a website they would like to block and then that which they typed would be added to their computer’s hostsfile, thereby making it so that the individual will not be able to access that particular website.

In other words, I want to insert the answer of inputbox function into an array and then export the strings from that array onto another file.

Here is my code as of now, it doesn’t do anything but ask the two questions given by the inputbox boxes—it doesn’t write that which was inputted into the boxes into the hostsfile. What exactly is wrong and how can i fix it?

Thank you very much for your answers

dim result
dim sites
x = 0
Do
  Set sites = CreateObject("System.Collections.ArrayList")
  result = Inputbox("What site do you wanted blocked? Please include entire address.") 
  result2 = MsgBox("Would you like to add another site at this time?", vbQuestion + vbYesNo)
      If result2 = vbNo Then
           Exit Do
      End If
  sites.add result
Loop
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Hosts = FSO.GetFile("C:\Windows\System32\drivers\etc\hosts")
set oapp = FSO.OpenTextFile("C:\Windows\System32\drivers\etc\hosts", 8, true)
    for x = 0 to sites.Count -1
        site = sites(x).ToString
        oapp.WriteLine ("0.0.0.0" & site)
    next

Solution

  • The arraylist sites should be initialized before the loop, otherwise it is always reset.

    sites.add should be put before the Exit Do, else the last result will not be included.

    Dim result
    Dim sites
    Set sites = CreateObject("System.Collections.ArrayList")
    Do
      result = Inputbox("What site do you wanted blocked? Please include entire address.") 
      sites.add result
      result2 = MsgBox("Would you like to add another site at this time?", vbQuestion + vbYesNo)
      If result2 = vbNo Then
        Exit Do
      End If
    Loop
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set oapp = FSO.OpenTextFile("C:\Windows\System32\drivers\etc\hosts", 8, true)
    For x = 0 to sites.Count -1
        site = sites(x)
        oapp.WriteLine ("0.0.0.0 " & site)
    Next