Who Wants to Be a Scripting Guy?

The Weekly Scripting Puzzle

Weekly Scripting Puzzle

February 3, 2006: We Don’t Seem to Have the Write Stuff


Scripting? Why, we love scripting. It’s fantastic, we can’t think of a single bad thing to say about it. In fact, when it comes to scripting we –

OK, we admit it: although we really do think scripting is great, there’s no doubt that it does drive us crazy from time-to-time. For example, we’re in the process of writing a script that needs to periodically append information to a text file. Although we haven’t had much experience working with text files, we found some sample code on the Internet that allows us to read in the current contents of a text file and store that information in a variable (which we named strContents). Starting from there, we then added some code of our own that tacked additional information to the value of strContents, and then used the FileSystemObject to write these revised contents back to the text file. Here’s our little practice script that does all this:

On Error Resume Next

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile("c:\scripts\test.txt", 1)

Do Until objTextFile.AtEndOfStream
    strContents = objTextFile.ReadAll
Loop

strContents = strContents & vbCrLf & "This line was added at the end of the file."

Wscript.Echo strContents

objTextFile.Write strContents
objTextFile.Close

Thanks; we thought it was pretty nice, too. The only problem is, it doesn’t work. To start with, our text file consists of one line:

Here's the existing content in our file.

Our script can successfully open and read in the contents of that file. It can also append a second line (This line was added at the end of the file) to strContents. How do we know that? Well, just to be on the safe side, we included a line of code that echoes the value of the variable strContents. Here’s what we get when we call Wscript.Echo:

Here's the existing content in our file.
This line was added at the end of the file.

That’s perfect; it’s exactly what we want. Having successfully modified the value of strContents we then use the FileSystemObject’s Write method to write the new value to the text file. When we do that we don’t get any error messages; unfortunately, we also don’t get the new line of text appended to the text file. In fact, after running the script here’s what our text file looks like:

Here's the existing content in our file.

That’s right: it’s completely unchanged. We managed to modify the file contents in memory, but for some reason the script failed to modify the contents of the actual file itself. And yet we didn’t get any error messages telling us why we couldn’t do this. You know, sometimes scripting makes us so mad that we could just –

Um, by which we mean this: what’s wrong with this script?


Top of pageTop of page