Guy's Scripting Ezine 79 - FSO Part 2 Append Text
Contents for Ezine 79 - FSO Append Text
This week I am taking my own advice and building the script gradually. Last week we built stage 1, creating a folder and we also completed stage 2, creating a file. So this week it's the coup de grace, stage 3 appending text to the file we created earlier.
Scenario: We want to append text to file.
Let's assume that we wish to write WMI information to a file. Alternatively, we may wish to output Active Directory data into a text file. In both cases we need to employ an FSO method called OpenTextFile. (Not CreateTextFile)
This is a script that will execute equally well on a Windows server or an XP machine. To ensure that there are no permissions errors, I recommend that you logon as administrator.
Instructions for Creating a Folder
Here is the finished script, the fruits of two week's labor. It tests for the folder referenced by strDirectory, and then tests for the file name referenced by strFile. If necessary, the script will even create the folder or the file. Then we reach the key part, VBScript appends what ever value we set in strText to the end of the file. Note it appends to the file and does not over-write existing lines.
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.
Note 1: This is a complex example, which builds on last weeks scripts. See here for a refresher on creating a folder and file.
Note 2: As with many file scripts, the first task is to
create an object, in this case objFSO. Once we have the object then we can use it to manipulate the text, here is the classic FSO command:
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) strText. Examine carefully the CONST statement. This example uses: Const ForAppending = 8.
Note 4: Without adding these two lines the VBScript fails with a permissions error:
Guy's Challenge - Change Append to Over-write
I throw down the gauntlet, instead of appending data, can
you make the script delete the existing content and just write strText to the file? To help you get started, I changed
In this example VBScript employs FileSystemObject to create an object called objFSO. Once you have this FSO object then you can manipulate it with methods such as OpenTextFile. One more factor, choose the correct CONST statement. For Appending = 8, or for over-writing, ForWriting =2.
See more about scripting files with VBScript