VBScript throws "object variable not set" error - vbscript

Set sh = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim counter, myNum, fileLine
myNum = 0
counter = 9000000
Do While myNum < counter
myNum = myNum + 1
Call GetConnections()
Loop
Function GetConnections()
i = 0
outFile = "netband_logger_vbs.tmp"
Set objFile = objFSO.CreateTextFile(outFile, True)
Set shExec = sh.Exec("netstat -e")
Do While Not shExec.StdOut.AtEndOfStream
fileLine = shExec.StdOut.ReadLine()
objFile.Write fileLine & vbCrLf
objFile.Close
Loop
End Function
I have the VBScript above. What I want to do is to run the netstat -e command 9000000 times and write every line of output to a text file line by line. And each time the after the first round of executions have terminated the script should overwrite the previous content of the netband_logger_vbs.tmp file with the values from the new round of executions.
Currently I have two problems: I can't seem to write the entire output to my .tmp file and I am also faced with an "object variable not set" error.

The error you're getting is probably because you're closing the file handle after the first iteration. To fix this move the line objFile.Close after the loop.
With that said, I wouldn't recommend using the Exec method here anyway. In your scenario it's much easier to shell out to CMD and use output redirection:
sh.Run "%COMSPEC% /c netstat -e >""" & outFile & """", 0, True

As for why you can't get all the entire output into one file; the FAT32 filesystem has a 4GB cap, and if you're writing lot's of small .tmp files there's a directory cap.
And to prevent the file from being closed during a lapse in the StdOut stream move objFile.Close to after the Loop

Related

VBScript's Shell Command Will Not Execute Unless An Output File Is Specified

I'm trying to run a shell command for google speech recognition. I'm able to run the command only if I provide an output file to the command string.
As you can see my test code sample below, I would attach the ">outputFile" if one is provided and also coded in a timeout loop to abort the process after a set time limit.
strCommand = "cmd /c ipconfig /all"
If outputFile <> "" Then
strCommand = strCommand & " > """ & outputFile & """"
End If
Set wshShellExec = wshShell.Exec(strCommand)
expiration = DateAdd("s", 600, Now)
Do While wshShellExec.Status = WshRunning And Now < expiration
WScript.Sleep 5000
Loop
Select Case wshShellExec.Status
Case WshRunning
wshShellExec.Terminate
TestFunction = "{""error"": ""TestFunction Command Timed Out""}"
Case WshFinished
TestFunction = WshShellExec.StdOut.ReadAll()
Case WshFailed
TestFunction = wshShellExec.StdErr.ReadAll()
End Select
If I leave outputFile empty and try to expect the output to be returned from the function, all it does is sit still for 5 minutes before timing out and sending me my error message.
Why does it need an output file to run?
If I run the command line manually on a Command Prompt, it runs perfectly fine.
Output buffers have limited capacity. If your command writes too much text to stdout the buffer will fill up and block the command from writing more until you clear the buffer (e.g. by reading from it). ReadAll can't be used for that, though, because that method will only return after the command has finished and block otherwise, thus creating a deadlock.
Your best option is to redirect output to one or more (temp) files, and read the output from those files after the command has finished.
outfile = "C:\out.txt"
errfile = "C:\err.txt"
cmd = "cmd /c ipconfig /all >""" & outfile & """ 2>""" & errfile & """"
timeout = DateAdd("s", 600, Now)
Set sh = CreateObject("WScript.Shell")
Set ex = sh.Exec(cmd)
Do While ex.Status = WshRunning And Now < timeout
WScript.Sleep 200
Loop
Set fso = CreateObject("Scripting.FileSystemObject")
outtxt = fso.OpenTextFile(outfile).ReadAll
errtxt = fso.OpenTextFile(errfile).ReadAll
If you don't want to do that for some reason you must read from StdOut repeatedly.
outtxt = ""
errtxt = ""
cmd = "ipconfig /all"
timeout = DateAdd("s", 600, Now)
Set sh = CreateObject("WScript.Shell")
Set ex = sh.Exec(cmd)
Do While ex.Status = WshRunning And Now < timeout
WScript.Sleep 200
outtxt = outtxt & ex.StdOut.ReadLine & vbNewLine
Loop
Note that you may also need to read from StdErr, because that buffer might fill up too if there is too much error output. However, reading both buffers might create another deadlock, because IIRC ReadLine blocks until it can read a full line, so if the script might hang waiting for error output that never appears. You might be able to work around that by using Read instead of ReadLine, but it'll still be very fragile.
So, again, your best option is to redirect command output to files and read those files after the command terminates.
Once the wshShellExec is terminated in the WshRunning case, instead of assigning the error message, the output should be assigned.
Select Case wshShellExec.Status
Case WshRunning
wshShellExec.Terminate
TestFunction = "Terminated: " & vbcrlf & WshShellExec.StdOut.ReadAll()
Case WshFinished
TestFunction = "Finished: " & vbcrlf & WshShellExec.StdOut.ReadAll()
Case WshFailed
TestFunction = wshShellExec.StdErr.ReadAll()
End Select

The OpenTextFile is overriding opened text file by clearing it

I am currently having a problem with OpenTextFile. I created a script over a year ago. Recently, the script started giving me problems. It's clearing the first text file and giving me an error.
Set objArgs = WScript.Arguments
myFile = objArgs(0)
numberofTXT = objArgs(1)
line = objArgs(2)
Set f = CreateObject("Scripting.FileSystemObject").OpenTextFile(myFile, line)
d = f.ReadLine
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile=numberofTXT
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write d & vbCrLf
objFile.Close
This is a super basic script I wrote to explain my issue. Takes in 3 files as arguments. For example LOL.txt, Hi.txt, and a specific line of LOL.txt (Why did 13-year-old me give examples using the word Lol, oh my gosh). This is meant to read the first file and write the data from the first file to the second file.
This issue was due to my current understanding (when I posted this) and not knowing what documentation was. I was self-taught. Please make sure to read the documentation if you have any issues with OpenTextFile and make sure your arguments are correct for the function.
Read and apply the OpenTextFile Method reference:
Opens a specified file and returns a TextStream object that can be
used to read from, write to, or append to the file.
Syntax
object.OpenTextFile(filename[, iomode[, create[, format]]])
Arguments
object   Required. Object is always the name of a FileSystemObject.
filename Required. String expression that identifies the file to open.
iomode   Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create   Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value
is True if a new file is created, False if it isn't created. If
omitted, a new file isn't created.
format   Optional. One of three Tristate values used to indicate the format of the opened file (TristateTrue = -1 to open the file as
Unicode, TristateFalse = 0 to open the file as ASCII,
TristateUseDefault = -2 to open the file as the system default). If
omitted, the file is opened as ASCII.
Settings
The iomode argument can have any of the following settings:
Constant Value Description
ForReading 1 Open a file for reading only. You can't write to this file.
ForWriting 2 Open a file for writing.
ForAppending 8 Open a file and write to the end of the file.
Read CreateTextFile Method reference as well. Then, the following commented code snippet could help:
Const ForReading = 1
Set objArgs = WScript.Arguments
myFile = objArgs(0) ' file to read
numberofTXT = objArgs(1) ' file to write
line = objArgs(2) ' line serial number to write into output file
' (or number of lines?)
Set objFSO = CreateObject("Scripting.FileSystemObject")
outFile=numberofTXT
Set objFile = objFSO.CreateTextFile(outFile,True)
Set f = objFSO.OpenTextFile(myFile, ForReading)
lineindex = 1
Do until f.AtEndOfStream
d = f.ReadLine
if lineindex = line Then ' only take the line-th line
objFile.Write d & vbCrLf ' or objFile.WriteLine d
Exit Do ' transfers control to the statement immediately following Loop statement
End If
lineindex = lineindex + 1
Loop
objFile.Close
f.Close

Read VBScript window for answer and execute into Batch

SETLOCAL ENABLEDELAYEDEXPANSION
curl "http://example.net/?u=%VARIABLE%" >> TXT.txt
wscript "C:\THAT.vbs"
start "" "http://url.com/%VARIABLE%"
exit
I have (above) batch file that runs CURL and writes output into a txt file.
And this (below) vbs file reads the content and shows message.
As you can see there is a start command in my batch file.
If I click Yes in vbs window I want to execute that start command.
If I click No in vbs window I want to go to exit.
Option Explicit
Const conForReading = 1
Dim objFSO, objReadFile, objFile, contents, result, shell, WshShell, somestring, txFldr2Open
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("TXT.txt")
If objFile.Size > 0 Then
Set objReadFile = objFSO.OpenTextFile("TXT.txt", 1, False)
contents = objReadFile.ReadAll
result = MsgBox ("HEADTEXT;" & vbCr & contents & "",vbYesNo+vbExclamation+vbSystemModal,"HEADQUESTION?")
Select Case result
Case vbYes
LET THE BATCH FILE KNOW ANSWER IS YES
Case vbNo
LET THE BATCH FILE KNOW ANSWER IS NO
End Select
objReadFile.close
Else
End If
Set objFSO = Nothing
Set objReadFile = Nothing
WScript.Quit()
It it possible to do that? If so how?
Use the exit code from vbscript to return the selection to batch script
batch file
SETLOCAL ENABLEDELAYEDEXPANSION
curl "http://example.net/?u=%VARIABLE%" >> TXT.txt
cscript //nologo "C:\THAT.vbs"
if not errorlevel 1 (
start "" "http://url.com/%VARIABLE%"
)
exit
that.vbs
Option Explicit
Const conForReading = 1
Dim objFSO, contents, result
result = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.GetFile("TXT.txt").Size > 0 Then
contents = objFSO.OpenTextFile("TXT.txt", 1, False).ReadAll
If MsgBox ("HEADTEXT;" & vbCr & contents & "",vbYesNo+vbExclamation+vbSystemModal,"HEADQUESTION?") = vbYes Then
result = 0
End If
End If
WScript.Quit result

VB script run time error input past end of file

I'm taking a scripting class and im having some issues with my script. According to the lab assignment all my syntax is correct. However i keep getting a input past end of file error on line 60,1. I've starred at the program forever and checked all lines letter for letter for quite some time with no luck. Any help would be greatly appreciated. Here is the script.
dim ipAddress(5,3)
ipAddress(0,0)="192.168.10.11"
ipAddress(0,1)="192.168.10.12"
ipAddress(0,2)="192.168.10.13"
ipAddress(0,3)="192.168.10.14"
ipAddress(1,0)="192.168.10.19"
ipAddress(1,1)="192.168.10.20"
ipAddress(1,2)="192.168.10.21"
ipAddress(1,3)="192.168.10.22"
ipAddress(2,0)="192.168.10.27"
ipAddress(2,1)="192.168.10.28"
ipAddress(2,2)="192.168.10.29"
ipAddress(2,3)="192.168.10.30"
ipAddress(3,0)="192.168.10.35"
ipAddress(3,1)="192.168.10.36"
ipAddress(3,2)="192.168.10.37"
ipAddress(3,3)="192.168.10.38"
ipAddress(4,0)="192.168.10.43"
ipAddress(4,1)="192.168.10.44"
ipAddress(4,2)="192.168.10.45"
ipAddress(4,3)="192.168.10.46"
ipAddress(5,0)="192.168.10.51"
ipAddress(5,1)="192.168.10.52"
ipAddress(5,2)="192.168.10.53"
ipAddress(5,3)="192.168.10.54"
const READ = 1
const WRITE = 2
const APPEND = 8
const ASCII = 0
dim fileName
fileName = "IP_Addresses.csv"
dim ipAddrStr
ipAddrStr = ""
dim fso
Set fso = Wscript.CreateObject("Scripting.FileSystemObject")
Set ipFileObj = fso.CreateTextFile(fileName,True,ASCII)
For room = 0 to 5
For computer = 0 to 3
ipAddrSr = CStr(room+100) & "," & CStr(computer+1) & "," ipAddress(room,computer)
& vbCrlf
ipFileObj.write(ipAddrStr)
Next
Next
ipFileObj.close
Set ipFileObj = fso.OpenTextFile(fileName,READ,ASCII)
WScript.Echo ipFileObj.ReadAll **' this is line 60**
ipFileObj.Close
As you don't use "Option Explicit", you get what you deserve: You (try to) concatenate the lines into ipAddrSr but write ipAddrStr to the file. So nothing gets written to the file.
Fix the syntax error and the bad name to:
ipAddrStr = CStr(room+100) & "," & CStr(computer+1) & "," & ipAddress(room,computer) & vbCrlf
Assuming that the file isn't empty, perhaps you need to specify the directory the file is in? I think this can be done either in your script:
fileName = "c:\your_directory\IP_Addresses.csv"
Or if you run it in the command line via cscript...
cscript.exe your.vbs "c:\your_directory\IP_Addresses.csv"
You can check the file size before executing your Echo if you like...
if fileName.size > 0 then
Set ipFileObj = fso.OpenTextFile(fileName,READ,ASCII)
WScript.Echo ipFileObj.ReadAll **' this is line 60**
ipFileObj.Close
else
WScript.Echo = "File was empty"
end if
See details of passing an argument to your script here.

vbScript to execute all files in a dir

I'm trying to write a vbScript that will execute all files in a given directory (will be mostly batch files).
I've tried to modify a script that deletes all files but I'm not able to get it to work.
Here is what I have:
Option Explicit
'===========================================================================
' Scheduled Task - Visual Basic ActiveX Script
'===========================================================================
Call ExecuteDirectory("c:\users\public\documents\schedule\daily")
Function ExecuteDirectory(strPath2Folder)
Dim fso, f, fc, f1, strFiles, intFiles
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
strFiles = ""
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(strPath2Folder)) Then
Set f = fso.GetFolder(strPath2Folder)
Set fc = f.Files
'-- Execute each file in Folder
For Each f1 in fc
strFiles = strFiles & f1.Name & vbCrLf
msgbox strPath2Folder & "\" & strFiles
WshShell.Run Chr(34) & strFiles & Chr(34), 1, true
Next
Set f1 = Nothing
Set fc = Nothing
Set f = Nothing
End If
Set fso = Nothing
End Function
The msgbox line displays the full path and file name that I want to execute, but the run line generates file not found error.
The variable strFiles continually builds up a list of files with line breaks in between. For example, if your folder contains the files "test1.bat" and "test2.bat", you will end up with this:
Iteration 1:
strFiles =
test1.bat
Iteration 1:
strFiles =
test1.bat
test2.bat
I don't think this is what you want to do. If you want to just run each script in order, you should just pass the single script name.
Try changing the inner loop to this:
For Each f1 in fc
Dim fileToRun
fileToRun = strPath2Folder & "\" & f1.Name
WshShell.Run Chr(34) & fileToRun & Chr(34), 1, true
Next
This is a very sloppy approach. If you are needing to execute an entire directory of batch files at one time, then you are not using them correctly. You should only need one batch file or one script an any time. I would begin looking at your whole system for a better approach to whatever it is that you are trying to accomplish.

Resources