Question

Vbscript to search string in a directory and output to a tab delimted file

Asked by: Matt_Tracker

VBscript needed to do a loop on a text file containing strings and search on all files(MS Office & OpenOffice formats) in  a directory (e.g C:\data) and output the results in a results.txt (tab delimited)

Example of  strings.txt

textA
textB
...
textZ

Example of results.txt

textA<tab>filepath1,filepath2
textB<tab>not found <!----if no results---->


Do note that the script is to be run on a hardened XP client computer with minimum rights (no admin rights etc.)

Thanks in advance

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-09-12 at 21:33:04ID23728404
Tags

Vbscript

Topics

Scripting Languages

,

VB Script

,

Windows XP Operating System

Participating Experts
3
Points
500
Comments
31

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Delimiting in VBScript
    I am trying to write a VBScript that takes a comma seperated Text file opens it in Excel and using the Excel Delimiter splits the text into columns.
  2. JavaScript or VBScript?
    What is the preferred scripting language used with ASP pages? JavaScript or VBScript?
  3. VBscript read delimited text file
    Hi, anyone have any examples or codes that shows how to read a delimited text file with column header and display the values in HTML using vbscript (without ASP)? kindly advise. Thanks. Regards, Isabel
  4. vbScript getElementById
    ASP3, trying to access an element id: Here is the element: <input type="TEXT" size="36" name="Contact Name" id="210"> And I am trying to do something simple in VBSCRIPT: dim el dim id id=210 el = document.getElementById(id) el....
  5. VBScript help: Loop through comma delimited string
    Hi All, I am not a VBScript guy but Dymo label is only called through VBScript: <SCRIPT LANGUAGE=VBScript> Sub Btn1_onclick() Dim DymoAddIn, DymoLabel, lAddress, lnbrOfLabels Set DymoAddIn = CreateObject("DYMO.DymoAddIn") Set DymoLabel = CreateObject(&q...
  6. VBscript to VBA
    Can this vbscript be modified to run in Excel VBA? Option Explicit Dim oJet 'As DAO.DBEngine Dim oDB 'As DAO.Database Dim oTDef 'As DAO.TableDef Dim blTExists 'As Boolean Dim strSQL 'As String Const DB_NAME = "C:\rubyfiles\tanks\gasdata.mdb" Const TBL_NAME = &q...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Matt_TrackerPosted on 2008-09-14 at 04:12:05ID: 22471878

or any other script will do that can do this in a winxp client without installing anything.

 

by: RobSampsonPosted on 2008-09-14 at 18:51:57ID: 22475516

Hi, try this VBS code.  You can set the first 4 lines to suit....

Regards,

Rob.

strSearchStrings = "C:\Temp\Scripts\Strings.txt"
strFolder = "C:\Temp"
strResultsFile = "C:\Temp\Scripts\Results.txt"
Const boolRecurse = True
 
strResults = "Searching for files in " & strFolder & ": " & Now
Const intForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDict = CreateObject("Scripting.Dictionary")
Set objInputFile = objFSO.OpenTextFile(strSearchStrings, intForReading, False)
While Not objInputFile.AtEndOfStream
	strString = objInputFile.ReadLine
	SearchFolder strFolder, strString
	If objDict.Exists(strString) = False Then objDict.Add strString, "Not found."
Wend
objInputFile.Close
Set objOutputFile = objFSO.CreateTextFile(strResultsFile, True)
objOutputFile.WriteLine strResults
For Each strSearchString In objDict
	objOutputFile.WriteLine strSearchString & vbTab & objDict(strSearchString)
Next
objOutputFile.Close
MsgBox "Done"
 
Sub SearchFolder(strFolderPath, strSearchFor)
	For Each objFile In objFSO.GetFolder(strFolderPath).Files
		If InStr(LCase(objFile.Name), LCase(strSearchFor)) > 0 Then
			If objDict.Exists(strSearchFor) = True Then
				objDict(strSearchFor) = objDict(strSearchFor) & "," & objFile.Path
			Else
				objDict.Add strSearchFor, objFile.Path
			End If
		End If
	Next
	If boolRecurse = True Then
		For Each objSubFolder In objFSO.GetFolder(strFolderPath).SubFolders
			SearchFolder objSubFolder.Path, strSearchFor
		Next
	End If
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:

Select allOpen in new window

 

by: Matt_TrackerPosted on 2008-09-15 at 06:51:18ID: 22478509

it didn't work

i had some excel and openoffice files with the following text
192.168.1.100
192.168.1.101
192.168.1.103
192.168.1.102
test

and the out put

Searching for files in C:\Temp: 15/09/2008 9:49:56 PM
192.168.1.100      Not found.
192.168.1.101      Not found.
192.168.1.103      Not found.
192.168.1.102      Not found.
test      Not found.

 

by: RobSampsonPosted on 2008-09-15 at 14:28:06ID: 22483107

Oh....I thought we were looking for file *names*, not the content of such files.....

I wasn't aware of how to search inside Office files using VBScript, until a few minutes ago, when I found this:
http://www.microsoft.com/technet/scriptcenter/resources/qanda/aug07/hey0827.mspx

which has been around since August 2007, so I missed the boat on that one :-[

Anyway, that does require the Windows Desktop Search 3.0 to be installed, but will definately do this job for you....

Regards,

Rob.

 

by: Matt_TrackerPosted on 2008-09-16 at 06:16:44ID: 22488032

sorry Rob - i did mention XP client machine with no admin rights as such i'm unable to install Window Desktop Search 3.0 and award points. thanks for the comments tho.

 

by: RobSampsonPosted on 2008-09-16 at 23:06:12ID: 22495858

I'm sorry, I don't know of any other way to programatically return the results from such a search, without using some additional software.

This is all I could find:
http://msdn.microsoft.com/en-us/library/bb266517(VS.85).aspx

Regards,

Rob.

 

by: Matt_TrackerPosted on 2008-09-19 at 00:56:51ID: 22518786

ok thanks. - is there any way to bump this question to expert or intermediate level

 

by: RobSampsonPosted on 2008-09-20 at 21:53:45ID: 22533300

Not sure.  You could try posting a request to have an alert sent to other experts for this question.....

 

by: b0lsc0ttPosted on 2008-09-22 at 09:34:33ID: 22541518

Does this have to be in vbscript?  Could you make an app and install it to be used?  Not all program installs will even need admin rights but can you not install a program for them, as an admin, and then it is there for them to use as their limited user?

To my knowledge RobSampson is exactly right ... vbscript needs help to do this.  Remember those files are binary and in a proprietary format.  It isn't something vbscript can just open and read (or at least make sense of).  RobSampson mention a program you could add that would let you do this in a vbscript.  I know of programs that will do this (e.g. PowerGrep) on their own and allow you to make the tab delimited file of the results.  Let me know if you want more details about that or similar programs, if you think it will be something you can use.

All credit to RobSampson though for most of this since I am just agreeing for the most part.  You can certainly leave this open to see if another expert can think of something that would fit your requirements.  I wanted to post a response so you knew the info you have so far seems very good and accurate.  Let me know if you have a question about any of this and good luck.  Hopefully this helps. :)

bol

 

by: DanRollinsPosted on 2008-09-22 at 10:34:11ID: 22542093

It seems to me that one way to approach this is to read the entrie file into a string variable, then use functions such as:

  InStr Function
  http://msdn.microsoft.com/en-us/library/wybb344c(VS.85).aspx

  Regular Expression (RegExp) Object
   http://msdn.microsoft.com/en-us/library/yab2dx62(VS.85).aspx

...to look for matches. I'd try
   OpenTextFile http://msdn.microsoft.com/en-us/library/314cz14s(VS.85).aspx
   ReadAll          http://msdn.microsoft.com/en-us/library/t58aa4dd(VS.85).aspx

Yes, these files are binary, but they likely contain the text itself in a recognizable form.

One way to quickly test if the above is true, use the following command-line:

FIND "192.168.1.100" c:\mydir\FileToSearch.doc

if FIND can find the text, then VBS probably can.

 

by: b0lsc0ttPosted on 2008-09-22 at 15:23:30ID: 22544842

VM,
Do you not want us to post more until then?  I would think any security issue would just mean our script won't find files the user may want because the machine is "hardened" and the script can't access the files.  I hope my comment below won't be too much but let me know if you have a concern and want us to hold until the Asker responds.

All,
In relation to DanRollins' suggestion I can say from some experience that trying the doc (and other formats) can be a little hard, even though there is some recognizable text.  In the case of a DOC file (in format of Word 97-02) you can see the lines but the new line characters isn't what most scripts would expect.  I believe it is just the CR character (chr 13).  If the script grabs all the contents then that may not matter but trying to read a "line" will not work well on a Windows system expecting CR+LF (or even just LF).  Of course that was just one DOC format (not the Word 2007 formats) and other Office files will be even harder.  I am not saying it won't work or provide what you want but just pointing out a basic issue.  Definitely worth mentioning by DanRollins and may be enough to work. :)

bol

 

by: RobSampsonPosted on 2008-09-22 at 15:59:56ID: 22545072

I agree with bol, I would expect that security still holds for the user context running the script or program, as to whether they can access certain files.  Also, in support of whether FileSystemObject methods would work, it seems unlikely (or at least quite complicated), as the Scripting Guys mention here:
http://www.microsoft.com/technet/scriptcenter/resources/qanda/aug07/hey0827.mspx

"Windows Desktop Search can open  and search through  all sorts of file types, including Word documents, Excel spreadsheets, PowerPoint presentations, etc. Without using Desktop Search wed be limited to searching through text files. (OK, in theory we could search other document types, but wed have to include code that identifies, opens and searches Word documents plus code that identifies, opens and searches Excel spreadsheets plus code that identifies, opens and searches  well, you get the idea.)"

The Windows Desktop Search can also be silently installed, and Group Policy controlled, as described in the Notes section here:
http://www.appdeploy.com/packages/detail.asp?id=678

The basic solution I think, is that this functionality requires a third party product (or at least an add-on), and I feel that using a Microsoft product would stick with most organisations guidelines too.

P.S. Thank Vee for the comments, and bol and Dan for the support.

Regards,

Rob.

 

by: DanRollinsPosted on 2008-09-22 at 22:11:13ID: 22546582

If a class of users were allowed read-only access to certain folders, some would consider that to be a soundly secure setup.  And there would be no constraints against searching though those documents to look for keywords or other data.

 

by: Matt_TrackerPosted on 2008-09-23 at 05:07:40ID: 22548348

thanks for all the comments.

currently i'm doing a word or text search using windows search tool to solve my problem.
( not desktop 3.0 as i do not have admin rights to install.)

i'm able to find the files easily with a single search, the problem i have is i need to do multiple searches.
and i have a long list and it's going to take me a long time to type in 1 by 1 and gather all the files displayed.

the hardening issue is confusing everyone. sorry-
i have full access rights to the files that i'm going to search.

i just need some code to read thru the list and create another file with the filepaths of documents found.(either vbs or something that can be run on xp pro without installing anything xtra).

if the code can run on my home xp pro computer without installing anything i'll be glad to award points.
even if it doesn't work on my hardened office computer.

 

by: Matt_TrackerPosted on 2008-09-23 at 07:36:43ID: 22549839

i can't copy the data out  - :( its encrypted

anyway i think we've hit a dead end here. so i'm willing to award points if there's any other solutions. (i.e copy the data files out to a machine where i have admin rights)

i just have to find a way to get the data files out decrypted....

thanks once again.

 

by: DanRollinsPosted on 2008-09-23 at 16:39:23ID: 22555376

It appears that command-line utilities such as FIND and FINDSTR fail on binary files such as *.doc (these tools expect line-oriented text).  

FWIW, the Visual Studio "Find In Files" command will let you search a branch or sub-tree of folders for files containing a specific text string.  You can limit the search to a list of file extensions.   The output pane shows each occurrence,.. and it does search binary data files.

 

by: RobSampsonPosted on 2008-09-23 at 19:02:30ID: 22556026

I'm out of ideas.  On your restricted PC (I assume it's at your work place)....can you get someone who *does* have admin rights to install the WDS for you?  That way, you could use a script.

If it's going to save you so much time, surely it would be in your organisation's best interests to do this for you?  If not, I really don't believe Windows can do it via script "out of the box".

Regards,

Rob.

 

by: Matt_TrackerPosted on 2008-09-24 at 08:36:56ID: 22560808

thanks once again for the comments

i'll award points for a script that works with Windows Desktop Search.
that fits the requirements in my first post.

 

by: RobSampsonPosted on 2008-09-24 at 17:23:12ID: 22565271

Hi, this will use Windows Desktop Search (I actually tested with version 4, which is now available) to find search terms from SearchStrings.txt, search files from a specific folder (recursively), and output results to Results.txt

Regards,

Rob.

'On Error Resume Next
 
strSearchStringsFile = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "SearchStrings.txt"
strResultsFile = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "Results.txt"
strFolder = "C:\Temp"
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
 
objConnection.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
 
strResults = "Searching " & strFolder & " at " & Now
Set objSearchFile = objFSO.OpenTextFile(strSearchStringsFile, intForReading, False)
While Not objSearchFile.AtEndOfStream
	strSearchFor = objSearchFile.ReadLine
	strSQL = "SELECT System.ItemPathDisplay FROM SYSTEMINDEX " & _
		"WHERE Contains('" & strSearchFor & "') " & _
	    "AND System.ItemPathDisplay LIKE '" & strFolder & "%'"
	objRecordSet.Open strSQL, objConnection
	
	If Not objRecordSet.EOF Then
		objRecordSet.MoveFirst
		Do Until objRecordset.EOF
		    strFilePath = objRecordset.Fields.Item("System.ItemPathDisplay")
		    strResults = strResults & VbCrLf & strSearchFor & vbTab & strFilePath
		    objRecordset.MoveNext
		Loop
	Else
		strResults = strResults & VbCrLf & strSearchFor & vbTab & "NOT FOUND"
	End If
	objRecordSet.Close
Wend
 
strResults = strResults & VbCrLf & "Finished searching " & strFolder & " at " & Now
Set objResultsFile = objFSO.CreateTextFile(strResultsFile, True)
objResultsFile.Write strResults
objResultsFile.Close
Set objResultsFile = Nothing
 
MsgBox "Finished searching " & strFolder & VbCrLf & "Please see " & strResultsFile

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

Select allOpen in new window

 

by: Matt_TrackerPosted on 2008-09-24 at 23:12:45ID: 22566613

any idea why  WDS doesn't index and find Openoffice formats even tho it has been specified in the file types?

 

by: RobSampsonPosted on 2008-09-25 at 00:21:20ID: 22566890

Hmmm. Not really....perhaps "Microsoft" doesn't know how to search "OpenOffice" files  :-(

 

by: Matt_TrackerPosted on 2008-09-25 at 06:54:16ID: 22569091

hi RobSampson

you code works , however its only getting single files.

for e.g there are 2 files with the searchstring but it only grabs the first 1 filepath.

is it possible for you to tweak the code so that it add the other filepath after a tab.

 

by: RobSampsonPosted on 2008-09-25 at 15:45:33ID: 22574749

Hi Matt, during my testing, I found it had the same behaviour, until I opened the full Desktop Search interface, and performed the search manually.  This forced the Desktop Search to index the target folder, and after that, the VBScript worked.  I think by default the Desktop Search is configured to only index when the system is idle, so it would take a while for it to index your file system.

Regards,

Rob.

 

by: Matt_TrackerPosted on 2008-09-25 at 20:07:34ID: 22576278

yes i realised that too. have to rebuild the index.
I also found out that ifilter plugin need to be installed before WDS can index Openoffice formats.
http://www.ifiltershop.com/staroffice-openoffice-ifilter.html

thanks alot for your solution

 

by: RobSampsonPosted on 2008-09-25 at 21:18:15ID: 22576565

Ah, yes.  Great work.  That appdeploy.com link I posted did mention something about an ifilter.....

Thanks for the grade.

Regards,

Rob.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...