How to Write Data to a File with OpenTextFile

VBScript Write File

This page deals specifically with writing data to a file using VBScript.  Once you have successfully created your FileSystemObject then you have the choice of reading, writing or appending data.  Whilst my examples are trivial, if you imagine this script as part of larger scripting project, then you will appreciate the power of the OpenTextFile.WriteLine method.

Topics for Writing or Appending to a File with VBScript

This page is the climax of our three tasks.  If you have been with me from the start, you may remember that we first created the parent folders.  Then secondly, we created the child files, now here we are going to read, write or append text data.  (If necessary have a refresher on Part 1 or Part 2.)

 ♦

Our Mission and GoalVBScript sample to write to files with ForAppending and opentextfile

This is the final part of our quest to control the output of a VBScript.  Often, at least in testing, you can just echo output data to a message box.  However, for complex production scripts, it is far better to write that data into a text file using the OpenTextFile method.

I imagine that most of the time you want to write or append data to a text (.txt) file; if so then FileSystemObject and OpenTextFile are the commands to learn.  However, even though you can also amend OpenTextFile to read data; in my opinion, I would prefer to employ the CreateObject("Excel.Application") method for reading text into a script.  In summary, it’s a case of horses for courses, OpenTextFile for writing, Excel.Application for reading.

Example – VBScript to Append Text to a File

This is a long script, therefore I suggest that you break it up into sections.  The best approach is to identify the create folder and create file sections, which are discussed on other pages (see menu top left).  Even though our mission is to write text to a file, our script must consider the folder’s location and also remember that text has a parent object, the file.   While the final bonus or cosmetic section is not strictly necessary, I like file scripts to open explorer so that I can check what has happened.

Before we start, there are three variations of the OpenTextFile method:

  1. Reading the text.
  2.  Writing text (perhaps I should say over-writing text).
  3. Appending data, as in the example below which we will examine in detail.

VBScript controls which variation of OpenTextFile you get with constants.  Indeed, ‘CONST’ is a VBScript subject in its own right.  However, for the purposes of this script, I suggest that you just accept the CONST values and focus on the OpenTextFile object and the .WriteLine method.

‘ OpenTextFile Method requires a Const value
‘ ForAppending = 8   ForReading = 1,   ForWriting = 2
For this script I choose: ForAppending = 8

Prerequisites

This is a script that will execute equally well on a Windows server or an XP machine.  Should you get permission errors, I recommend that you logon as administrator.

Instructions for Creating Files

  1. Copy and paste the example script below into notepad or a VBScript editor.
  2. Decide whether to change the value for strDirectory, strFile and strText.
  3. Save the file with a .vbs extension, for example: NewTextEC.vbs 
  4. Double click NewTextEC.vbs and check Windows Explorer for strDirectory.

Example Script to Append Text to a File

 

‘ NewTextEC.vbs
‘ Sample VBScript to write to a file. With added error-correcting
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ VBScript Write File
‘ ———————————————‘

Option Explicit
Dim objFSO, objFolder, objShell, objTextFile, objFile
Dim strDirectory, strFile, strText
strDirectory = "e:\logs3"
strFile = "\Summer.txt"
strText = "Book Another Holiday"

‘ Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

‘ Check that the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
   Set objFolder = objFSO.GetFolder(strDirectory)
Else
   Set objFolder = objFSO.CreateFolder(strDirectory)
   WScript.Echo "Just created " & strDirectory
End If

If objFSO.FileExists(strDirectory & strFile) Then
   Set objFolder = objFSO.GetFolder(strDirectory)
Else
   Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
   Wscript.Echo "Just created " & strDirectory & strFile
End If

set objFile = nothing
set objFolder = nothing
‘ OpenTextFile Method needs a Const value
‘ ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 8

Set objTextFile = objFSO.OpenTextFile _
(strDirectory & strFile, ForAppending, True)

‘ Writes strText every time you run this VBScript
objTextFile.WriteLine(strText)
objTextFile.Close

‘ Bonus or cosmetic section to launch explorer to check file
If err.number = vbEmpty then
   Set objShell = CreateObject("WScript.Shell")
   objShell.run ("Explorer" &" " & strDirectory & "\" )
Else WScript.echo "VBScript Error: " & err.number
End If

WScript.Quit

‘ End of VBScript to write to a file with error-correcting Code

VBScript Tutorial – Learning Points

Note 1:  This is a complex script built from two other scripts.  If you have not done so already, you may wish to check:
See here for a refresher on creating a folder
See here for a refresher on creating a file.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Orion performance monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Note 2:  As with many file scripts, the first task is to create an object.  Once we have that crucial object then we can persuade it to manipulate the text, here is the classic FSO command:
Set objFSO = CreateObject("Scripting.FileSystemObject").  Once we create objFSO we can GetFolder and CreateTextFile.

Note 3:  The central point of this script is the OpenTextFile method.  What we must also do is control whether to read, write or append (as in this case).  Examine carefully the CONST statement.  This example uses:
Const ForAppending = 8.
However, if you wish to over-write the text in the file, the command is ForWriting = 2, (not ForAppending = 2.

Note 4:  You may well be asking, what is the point of an example such as this script?  Well, try and imagine a WMI script that has interrogated the operating system for disk information.  Would it not be better to write the complex data to a file than merely echo the output to your screen?

Note 5:  Without adding these three lines this VBScript example fails with a permissions error:

objFile.Close
set objFile = nothing
set objFolder = nothing

Solarwinds Config GeneratorGuy Recommends: The Free Config Generator

SolarWinds’ Config Generator is a free tool, which puts you in charge of controlling changes to network routers and other SNMP devices.  Boost your network performance by activating network device features you’ve already paid for.

Guy says that for newbies the biggest benefit of this free tool is that it will provide the impetus for you to learn more about configuring the SNMP service with its ‘Traps’ and ‘Communities’. Try Config Generator now – it’s free!

Download your free copy of Config Generator

PowerShell Out-File – Alternative to VBScript Write File

Writing the results of a PowerShell command into a file is easy with out-File.  The biggest danger is ‘over-think’; just remember that PowerShell takes care of opening and closing the file automatically.  Consequently, there is no need to waste time looking for non-existent open-file, or save-file commands.  If the file specified by out-File does not already exist, PowerShell even creates it for you.

This is how the command works.  Assuming the first part of the script delivers the results, redirect the PowerShell output to a file with a command such as:
PowerShell-Command | out-File c:\ logs\result1.txt.

Example – Starting with Out-File

This example is purely to concentrate on the out-File command.  In fact, the sooner we move on to example 2, the sooner we can do some real work.

# PowerShell write to text file
Get-ChildItem "C:\Windows\System32" | out-File "D:\Files\Sys32.txt"

Note 1:  While out-File creates the file, you have to make sure that the path exists because out-File cannot create folders.  In this instance, the alternative is to adjust D: \files to C: \PS, or an existing folder on your machine.

See more about PowerShell Out-File

Summary of How to Append Data to a Text File

This is the definitive VBscript write file script.  I am sure that you will find many opportunities to adapt this VBScript code into a WMI script, or indeed any script which requires storing the output permanently in a file.

If you have already learnt how to create files and folders, then the OpenTextFile is the logical progression in controlling the data in the actual file.  By configuring the ‘CONST For xyz’, you can append data or over-write the existing file.  The real power and joy of this FSO technique comes in projects where you want to store the output data permanently in a text file.  Technically, the two key commands are FileSystemObject and OpenTextFile.

If you like this page then please share it with your friends

 


See more VBScript file examples:

VBScript to create folders   • VBScript to create files    • VBScript write file    • VBScript file copy

PowerShell OutFile   • PowerShell Get-ChildItem   • PowerShell create folder • Event Log Administrator

VBScript Event Log   • WMI Event Log • Event Log Example   • SolarWinds Log Event Manager