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.)
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.
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:
Reading the text.
Writing text (perhaps I should say over-writing text).
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
Copy and paste the example script below into notepad or a VBScript editor.
Decide whether to change the value for strDirectory, strFile and strText.
Save the file with a .vbs extension, for example: NewTextEC.vbs
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 http://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
Guy
Recommends: Permissions Analyzer - Free Active Directory Tool
I like the
Permissions Monitor because it enables me to see quickly WHO has permissions
to do WHAT. When you launch this tool it analyzes a users effective NTFS
permissions for a specific file or folder, takes into account network share
access, then displays the results in a nifty desktop dashboard!
Think of all the frustration that this free utility saves when you are
troubleshooting authorization problems for users access to a resource.
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
Guy
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'.
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.
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.
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
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems.
Fortunately, Solarwinds
have created the
Free WMI Monitor so that you can actually see and understand these gems of
performance information. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.