logo
Published on developer.* Blogs (http://www.developerdotstar.com/community)

VBScript Script to Copy/Swap Windows hosts File (Windows Script Host)

By Daniel Read
Created 2006-01-10 17:43

The following script can be used to swap a Windows hosts [1] file (located in System32\drivers\etc). For example, if you need to have different hosts files for different situations (for example, when logged onto a certain network that is using split brain DNS [2]) then you can use this script to swap them out. Make as many different hosts files as you need, give them unique extensions, and put them in the same folder as your hosts file. Then you can use this script to swap the files in and out. Pass the extension of the source file as the argument to the script. This script uses Windows Script Host (WSH). It's a quick-and-dirty script so takes a few shortcuts as far as readability. Some of the lines may wrap in this display also. Copy and paste into a text file and save with a .VBS extension.

Example usage:

SwapHosts.vbs CUSTOM

Where "CUSTOM" the extension of a copy of a hosts file in the same directory as the real hosts file.

Here is the script:

Option Explicit

Const HOSTS_DIR = "C:\WINDOWS\system32\drivers\etc\"

Dim FSO
Dim WSArgs
Dim strCopyFromExtension

Set WSArgs = WScript.Arguments
If WSArgs.Count > 0 Then
strCopyFromExtension = Trim(WSArgs(0))
Else
MsgBox "You must pass the extension of this hosts file you want " & _
"to copy from as an argument to this script.", vbExclamation
WScript.Quit 1
End If

If Not Len(strCopyFromExtension) > 0 Then
MsgBox "You must pass the extension of this hosts file you want to " & _
"copy from as an argument to this script.", vbExclamation
WScript.Quit 1
End If
If Left(strCopyFromExtension, 1) <> "." Then
strCopyFromExtension = "." & strCopyFromExtension
End If

Set FSO = CreateObject("Scripting.FileSystemObject")

If FSO.FileExists(HOSTS_DIR & "hosts" & strCopyFromExtension) Then
'Back it up first
FSO.CopyFile HOSTS_DIR & "hosts", HOSTS_DIR & "hosts" & strCopyFromExtension & ".BAK", True

'Then copy over
FSO.CopyFile HOSTS_DIR & "hosts" & strCopyFromExtension, HOSTS_DIR & "hosts", True

MsgBox "File " & "hosts" & strCopyFromExtension & _
" copied over the hosts file, which was back up as " & _
HOSTS_DIR & "hosts" & strCopyFromExtension & ".BAK" & ".", vbInformation
Else
MsgBox "Could not find " & HOSTS_DIR & "hosts" & strCopyFromExtension & ".", vbExclamation
WScript.Quit 1
End If

Set FSO = Nothing

Comments welcome. I am co-author, by the way, of the VBScript Programmer's Reference, Second Edition [3], which is a great resource for pretty much everything VBScript--starting with a ground-up programming tutorial, including advanced topics like classes, error handling and debugging, and script components, and covering just about every context, from ASP to the Windows Script Control.

Dan


Source URL:
http://www.developerdotstar.com/community/community/node/322