Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a file line by line in VB Script?

I have the following to read a file line by line:

wscript.echo "BEGIN"

filePath = WScript.Arguments(0)
filePath = "C:\Temp\vblist.txt"
Set ObjFso = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFso.OpenTextFile(filePath)
StrData = ObjFile.ReadLine
wscript.echo "END OF FIRST PART"

Do Until StrData = EOF(ObjFile.ReadLine)
    wscript.echo StrData
    StrData = ObjFile.ReadLine
Loop

wscript.echo "END"

The EOF() function doesn't seem to work:

C:\Users\EGr\Documents\Scripts\VB>cscript testloop.vbs ArgVal
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

BEGIN
END OF FIRST PART
C:\Users\EGr\Documents\Scripts\VB\testloop.vbs(11, 1) Microsoft VBScript runti
me error: Type mismatch: 'EOF'

I haven't programmed in VB before, but I'm trying to figure out loops so that I can modify a VB script I've been handed. I want to read a file line by line, and do something with each line. If I change the Do Until loop to Do Until StrData = EOF, it works but throws an error when it gets to the end of the file:

C:\Users\EGr\Documents\Scripts\VB>cscript testloop.vbs ThisRANDOMValue
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

BEGIN
1
END OF FIRST PART
host1
host2
host3
C:\Users\EGr\Documents\Scripts\VB\testloop.vbs(13, 2) Microsoft VBScript runti
me error: Input past end of file

I feel like there is probably an easy solution, but I haven't been able to find it. I've tried a few other solutions I've found online, but haven't got as close as the above.

like image 293
EGr Avatar asked Mar 20 '13 19:03

EGr


People also ask

How do I view a VB Script?

How to open a VBS file. You can open and edit VBS files using any text editor, such as Notepad++ (Windows), Apple TextEdit (Mac), or GitHub Atom.

What is VB scripting language?

VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It allows Microsoft Windows system administrators to generate powerful tools for managing computers with error handling, subroutines, and other advanced programming constructs.


1 Answers

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close
like image 102
Ansgar Wiechers Avatar answered Nov 18 '22 19:11

Ansgar Wiechers