Edit Hosts File with VB Script (VBS)
The easiest way to block websites on your home computer is through the hosts file or you may also use OpenDNS for blocking adult sites.
However, when you wish to block time-wasting sites only for a temporary period, this VB Script should help. Run it once to block the site and run it again to unblock them.
0:
1: 'Add the list of time wasting websites here
2: WebsitesToBlock = Array("twitter.com", "www.youtube.com", "www.facebook.com")
3:
4:
5: '-------------------------------------------------------------------
6: ' LetMeWork.vbs - Block Time Wasting Websites
7: ' Author: Amit Agarwal http://www.labnol.org/
8: ' This script will block /unblock time wasting sites with a click.
9: ' Internally, it will edit the Windows hosts file on your computer.
10: ' For suggestions, send me an email at amit@labnol.org
11: '-------------------------------------------------------------------
12: '-------------------------------------------------------------------
13:
14: If WScript.Arguments.length =0 Then
15: Set objShell = CreateObject("Shell.Application")
16: objShell.ShellExecute "wscript.exe", Chr(34) & WScript.ScriptFullName & Chr(34) & " RunAsAdministrator", "", "runas", 1
17: Else
18: Const ForReading = 1, ForWriting = 2
19:
20: Set shell = CreateObject("WScript.Shell")
21: root = shell.ExpandEnvironmentStrings("%systemroot%")
22: hostFile = root & "\\system32\\drivers\\etc\\hosts"
23: tempFile = hostFile & ".bak"
24:
25: blocked = 0
26: towrite = false
27:
28: Set fso = CreateObject("Scripting.FileSystemObject")
29: Set f1 = fso.OpenTextFile(hostFile, ForReading, True)
30: Set f2 = fso.OpenTextFile(tempFile, ForWriting, True)
31:
32: Do Until f1.AtEndOfStream
33:
34: line = f1.Readline
35: towrite = true
36:
37: For Each URL in WebsitesToBlock
38: If instr(line, URL) Then
39: If blocked = 0 Then
40: If left(line, 1) = "#" Then blocked = 1 Else blocked = 2
41: End If
42: towrite = false
43: End If
44: Next
45:
46: If towrite Then f2.WriteLine line
47: Loop
48:
49: For Each URL in WebsitesToBlock
50: If blocked <> 2 Then
51: f2.WriteLine "127.0.0.1" & vbTab & vbTab & URL
52: End If
53: Next
54:
55: fso.Copyfile tempFile, hostFile
56:
57: f1.Close
58: f2.Close
59:
60: If blocked = 2 Then
61: WScript.echo "Time wasting websites have now been unblocked!"
62: Else
63: WScript.echo "Time wasting websites are now blocked!"
64: End If
65:
66: End If
67:
68: ' By Amit Agarwal http://www.labnol.org/
69:
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory