web analytics

VBScript to search the file system for a text string

Options

davegate 143 - 921
@2016-01-08 10:45:22

The following VBScript code can be used to search the file system for a text string, the search result is saved into a text file named "results.txt".

'SearchTextString.vbs

'Set Error Handler
On Error Resume Next

'Define Objects
Set oshell = CreateObject("Shell.Application")
Set ofilesys = CreateObject("Scripting.FileSystemObject")
Set oscript = ofilesys.GetFile(WScript.ScriptFullName)
Set oargs = WScript.Arguments

'Get Folder
If oargs.Count >= 1 Then
 opath = oargs (0)
Else
 Set ofolder = oshell.BrowseForFolder(0, "Select a folder:", 0)
 Set ofolderitem = ofolder.Self
 opath = ofolderitem.Path
 If Err <> 0 Then WScript.Quit 
End If

'Get Search String
If oargs.Count >= 2 Then
 searchstr = oargs(1)
Else
 searchstr = Inputbox("Enter a search string:")
End If
If searchstr = "" then WScript.Quit

'Search Text Files For String
Set ofolder = ofilesys.GetFolder(opath)
Set ofiles = ofolder.files   
count = 0
Set oresults = ofilesys.CreateTextFile (oscript.parentfolder&"\results.txt", True)
For Each ofile In ofiles
 line = 0
 Set ofileinst = ofilesys.OpenTextFile(ofile, 1)
 Do Until ofileinst.AtEndOfStream
      str = ofileinst.Readline
  line = line + 1
  If (InStr(LCase(str), LCase(searchstr)) > 0) Then 
   count = count + 1
   oresults.WriteLine("File: " & ofile.path & ", Line: " & line)
   oresults.WriteLine(str)
  End If 
 Loop
 File.Close
Next
If count = 0 Then msgbox("String not found.") Else msgbox(count & " occurrences found.")

'Close File
oresults.Close

'Reset Error Handler
On Error Goto 0

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com