How Can I Read the Contents of a Text File and Then Declare the Contents as Variables?

ScriptingGuy1

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I read the contents of a text file, and then declare those contents as variables?

— TC

SpacerHey, Scripting Guy! AnswerScript Center

Hey, TC. Before we begin, did you really ask us this question? We’re positive that you did, but, the way things have been going lately, we can’t be too sure.

For example, by now everyone has heard that Scripting Guy Jean Ross went down to San Diego for the MMS conference, only to return with nearly a dozen surgical staples in her head.

Note. If you haven’t heard, Jean was taking a leisurely stroll through the San Diego Zoo when she noticed that a group of kindergarteners, on a field trip, had accidentally wandered into the grizzly bears’ compound. With complete and utter disregard for her own well-being Jean leaped over the fence, fought off the bears, and carried each and every child to safety. As it turned out, during the battle one of grizzlies took a swipe at Jean’s head and managed to inflict a nasty gash. After the children were all safe and sound, Jean – true to form – went back into the compound, performed first aid on the grizzly’s paw, and only then went to the hospital and had her own wound tended to.

But here’s the weird part (interestingly enough, for Jean getting her head stapled together wasn’t the weird part). The other day our Scripting Hero called the insurance company with a question about her claim; the insurance company told her that they had no record of her being treated in San Diego. Apparently she hadn’t had her head stapled back together while in San Diego!

It gets weirder. Last week the Scripting Guy who writes this column was writing this column when his computer died. When he tried restarting it (and he tried many times) he always got the same message: Non-system or disk error. At one point he did manage to get into the BIOS, thinking he would run the hard disk diagnostic test. What happened? Nothing: that option was grayed-out. Apparently the computer didn’t have a hard disk.

At that point the Scripting Guy who writes this column did what Scripting Guys always do in times of crisis: he went to lunch. When he came back he decided to try the computer one more time, just for the heck of it. Needless to say, it booted up just fine. He restarted it again, and again. No problem. He got back into the BIOS and discovered that his computer did have a hard disk; on top of that, it passed all the diagnostic checks with flying colors. Apparently his computer hadn’t died after all.

Very weird.

So, anyway, we can’t be sure, TC, that you actually asked a question about reading lines from a text file and then declaring that information as variables. However, if you did ask a question about reading lines from a text file and then declaring that information as variables here’s the answer.

Unless, of course, it turns out that we didn’t answer your question after all. But let’s try the following and see what happens:

Const ForReading = 1

Set objFSO = CreateObject(“Scripting.FileSystemObject”) Set objFile = objFSO.OpenTextFile(“C:\Scripts\Test.txt”, ForReading)

Do Until objFile.AtEndOfStream strLine = objFile.ReadLine Execute strLine Loop

objFile.Close

Wscript.Echo strFirstName Wscript.Echo strLastName

OK. If we understand your question (that is, the question you either did or did not ask), you have a text file with lines similar to this:

strFirstName = “Ken”
strLastName = “Myer”

As you can see, each line looks an awful lot like a line of code assigning a value to a variable; in fact, if you typed these lines as-is into a script you’d end up with a variable named strFirstName (with a value of Ken) and a variable named strLastName (with a value of Myer). Of course, you don’t want to type those lines as-is into a script; instead, you want to read those lines from a text file and then execute each line as if you had typed it into the script. In other words, you want your script to function as though you had typed in those two lines of code, even though you never actually typed in those two lines of code.

See? We told you everything was getting weird!

So how are we going to do all that (whatever it is)? Well, we’re going to start off by defining a constant named ForReading and setting the value to 1; that’s a constant we’ll need when we open the text file. After the constant has been defined we next create an instance of the Scripting.FileSystemObject object and then open the file C:\Scripts\Test.txt:

Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objFile = objFSO.OpenTextFile(“C:\Scripts\Test.txt”, ForReading)

Now for the good part. What we need to do next is read in the text file line-by-line, and then execute each line in the text file as though it was a line of code we had typed into our script. (Why do we keep using the verb “execute?” You’ll find out in just a second.) To do that, we first set up a Do Until loop designed to run until we reach the end of the text file (that is, until the file’s AtEndOfStream property is True). Inside that loop we use the ReadLine method to read the first line from the text file and then store that value in a variable named strLine:

strLine = objFile.Readline

Got that? That simply means that strLine is equal to this:

strFirstName = “Ken”

Is that going to help us? You bet it is. To create a variable named strFirstName, with a value of Ken, all we have to do now is call the Execute statement followed by the value to be executed:

Execute strLine

The Execute statement is a little-known yet interesting feature of VBScript; among other things, this statement enables you to execute a string value (or variable) as if you had typed that value into your script as a line of code. Confusing? Yes. But take a look at this sample script:

strMessage = “Hi”
strCode = “Msgbox strMessage”
Execute strCode

Here we’ve stored the text value Hi into a variable named strMessage. We’ve then assigned the following value to a variable named strCode:

Msgbox strMessage

And you’re right, that does look like a line of code for displaying the value of strMessage in a message box. And there’s a good reason for that: it is a line of code for displaying the value of strMessage in a message box. That’s the whole idea. In order to now run that line of code (that is, in order to display the message box) all we have to do is call the Execute statement followed by the string value (in this case, the variable strCode) we want to execute.

Give it a try and you’ll see what we’re talking about.

At any rate, when we call the Execute statement we end up executing this value:

strFirstName = “Ken”

And guess what? That’s going to create a variable named strFirstName and assign it the value Ken. And then we’re going to loop around and repeat this process with the next line in the text file.

Admittedly, this all sounds crazy. But look at what we get back when we echo back the values of strFirstName and strLastName:

Ken
Myer

Obviously strFirstName and strLastName are valid variables. And how do you suppose they got assigned their respective values? You got it: from the information found in the text file. Pretty cool, huh?

Admittedly, we’re not sure how often you’ll need to read lines of code from a text file and then declare those lines of code as variables. Nevertheless, there are times when the Execute statement is invaluable. What times? Well, for at least one example, see this event from the 2007 Winter Scripting Games.

Anyway, we hope that answers your question, TC. If it turns out that you didn’t actually ask us a question, well, that’s OK: the ways things have been going lately we’re not so sure we answered the question anyway. Have we mentioned the two Scripting Guys who signed up for TechEd 2007 and received emails confirming their registration, then a few days later received emails telling them that they hadn’t registered? Only then to be told that they did register after all. Only – well, never mind. Most likely none of that happened, either. Either way, we’ll see everyone at TechEd 2007.

Assuming, of course, that there is such a thing as TechEd 2007.

0 comments

Discussion is closed.

Feedback usabilla icon