Using VBScript To Search Inside Files
Search Inside Files
VBScript has a few powerful methods to search through different types of text files to acquire information. This information can be passed on to other scripts, used to make business decisions or even used to identify problems and come up with a resolution.
Some of the commonly used methods used by a VBScript programmer to search for text in files are instr, readline and .AtEndOfStream. Regardless of what method chosen, there are several ways to search a text file. Many programmers will use combinations of the methods described above, so there is really no right or wrong. What’s important is whether or not it works for the script being developed.
The following code simply searches within a file located at C:\temp\somefile.txt, looks for “User:” within each line in that file and if the “User:” string exists, it reads certain characters within that line and displays them within a messagebox.
The code is functional, full of comments, “’” and is intended to be used as an example. For learning purposes, and to reinforce text search methods, the code can be modified by changing the file being opened and searching for a different string inside the file.
VBScript Code to Search For a String Within a File
Dim objFSO, strLine, objReadFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Identifies the file being read.
Set objReadFile = objFSO.OpenTextFile("C:\temp\somefile.txt", 1, False)
'Reads the file until the end.
Do Until objReadFile.AtEndOfStream
'Sets the line being read to a variable named strLine.
strLine = objReadFile.ReadLine
'Trims the strLine variable to remove any leading or trailing spaces.
strLine = trim(strLine)
'Set the search condition. In this case, we're looking for "User:" in the string
'of text which was set to strLine.
if instr(strLine, "User:") Then
'If "User:" is found in the line of text, we're telling VBScript to move forward 7
'characters, take the next 29 characters and set that string to a variable named strLine.
strLine = Mid(strLine, 7, 29)
'trim the strLine variable to remove any leading or trailing spaces.
strLine = trim(strLine)
set objFSO = nothing
More by this Author
Don’t overlook the power of this scripting language! Administrators, developers, analysts and others have all discovered the power of Microsoft VBScript. VBScript, sometimes called “VBScripting” is a...
Applications make use of environment variables either by writing to or reading from them at different times during the runtime of a program. System administrators, IT analysts and anyone else using VBScript, can take...
Learn how to get rid of the musty, mildew-y smell coming from your window AC unit and stop the stink!
No comments yet.