Ndy daniel
Ndy daniel

Reputation: 77

VBScript throws "object variable not set" error

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.

Upvotes: 1

Views: 1349

Answers (2)

Steven Black
Steven Black

Reputation: 2232

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

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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

Upvotes: 1

Related Questions