Question

Need VB Script to look for a file and act on if it exists

Asked by: jsvb1977

I have a tiny script that looks in a directory for a file. I need to modify the script so that it does the following:

1. If the file exists, END
2. If the file does not exist, wait 5 seconds and look again.

I think it would be bad to loop the script for ever so I would also like to limit the number of loops so that if the file never exists, the script will END [or even better, throw an error or write to the event logs or something like that].

I have tried a couple of things without success. This is different than .Net, I think, so I'm not sure if I can use Sub to loop through.

FYI - this script will be used in an application that allows the use of vb script so it will not be a stand alone application or anything like that [if it matters].

Thank you,
Jason

strFile= "C:\Scripts\JRSTEST.txt"
set objFSO = createobject("Scripting.FileSystemObject")
 
if objFSO.FileExists(strFile) then
	'Do Nothing
else
    wscript.echo "Sorry, the file does not exist"
end if

                                  
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

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
2009-10-29 at 08:38:21ID24854987
Tags

vb script

,

visual basic

Topics

VB Script

,

Visual Basic Programming

Participating Experts
3
Points
500
Comments
18

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. Stand alone Sybase
    I have a VB app that uses Sybase 11 running on a Unix server. I want to run the app stand-alone on a laptop (no network connection). What are my options? I have Sybase Adaptive Server Anywhere, but don't know if that will work and how to get my database migrated over.
  2. Stand alone application(VB) to access web server
    Hi all :) I need your expert advices on whether is it possible to let stand alone application like VB program to access web server to act like central database ? Thanks in advance! Rgrds, aili
  3. A stand alone without msvbvm60.dll
    Dear Experts, It seems all the visual basic stand alone files need msvbvm60.dll to run. But for some reasons I need to have a real STAND ALONE file. How can I make such a file? Please help me. Thanks.

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: BlueDevilFanPosted on 2009-10-29 at 08:55:02ID: 25695058

This should do it.

strFile= "C:\Scripts\JRSTEST.txt"
set objFSO = createobject("Scripting.FileSystemObject")
 
Do While Not objFSO.FileExists(strFile)
    WScript.Sleep 5000
Loop
WScript.Quit

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: egl1044Posted on 2009-10-29 at 08:59:54ID: 25695096

You can try something like this

CONST RETRY_COUNT = 1
CONST RETRY_TIMEOUT = 5000
 
Dim FSO
Dim strFile
Dim i
 
strFile = "d:\test.txt"
 
Set FSO = CreateObject("Scripting.FileSystemObject")
 
For i = 1 to RETRY_COUNT
If FSO.FileExists(strFile) Then
Exit For
Else
wscript.sleep(RETRY_TIMEOUT)
End If
Next

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: jsvb1977Posted on 2009-10-29 at 09:03:01ID: 25695126

BlueDevilFan:

Thank you! is there a way to control the number of times it loops so as to avoid the situation where the file never exists and the script loops forever?

Let me know if this is possible,
Jason

 

by: jsvb1977Posted on 2009-10-29 at 09:04:58ID: 25695148

egl1044:

i posted before i saw your post -- i will try your solution as well -- looks like you got the loop under control.

 

by: matthewspatrickPosted on 2009-10-29 at 09:06:00ID: 25695155

Hello jsvb1977,

Modified to include an escape after a specified time limit...

Regards,

Patrick

Dim strFile, objFSO, StartAt
Const MaxDelay = 900 '15 minutes, expressed in seconds
 
StartAt = Now
 
strFile= "C:\Scripts\JRSTEST.txt"
set objFSO = createobject("Scripting.FileSystemObject")
 
Do 
    If DateDiff("s", StartAt, Now) >= MaxDelay Then
        MsgBox "Quitting because I hit the limit", vbCritical + vbSystemModal, _
            "No soup for you!"
        Exit Do
    End If
    WScript.Sleep 5000
Loop Until objFSO.FileExists(strFile)
Set objFSO = Nothing
WScript.Quit

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: matthewspatrickPosted on 2009-10-29 at 09:06:52ID: 25695162

Sorry all, I didn't refresh before posting :)

 

by: BlueDevilFanPosted on 2009-10-29 at 09:10:33ID: 25695210

Here's my version with control.

strFile= "C:\Scripts\JRSTEST.txt"
lngLoops = 1
set objFSO = createobject("Scripting.FileSystemObject")
 
Do While Not objFSO.FileExists(strFile)
    WScript.Sleep 5000
    lngLoops = lngLoops + 1
    If lngLopps >= 5000 Then Exit Do
Loop
WScript.Quit

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: BlueDevilFanPosted on 2009-10-29 at 09:11:44ID: 25695225

Or another way

strFile= "C:\Scripts\JRSTEST.txt"
lngLoops = 1
set objFSO = createobject("Scripting.FileSystemObject")
 
Do While (Not objFSO.FileExists(strFile)) And (lngLoops < 5000)
    WScript.Sleep 5000
    lngLoops = lngLoops + 1
Loop
WScript.Quit

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: jsvb1977Posted on 2009-10-29 at 11:20:13ID: 25696556

Well,

I turns out that WScript calls can not be used in the application I intended to use this script for. Here is an article that gives an explanation:

http://support.microsoft.com/kb/279164

Is it possible to accomplish what I want to accomplish without referencing WScript Functions?

Let me know,
Jason

 

by: jsvb1977Posted on 2009-10-29 at 11:23:10ID: 25696589

FYI:

egl1044's solution worked perfectly OUTSIDE of the application I used it in.

Jason

 

by: BlueDevilFanPosted on 2009-10-29 at 11:28:30ID: 25696635

Jason,

You didn't say anything about needing this in an application.  What do you need to run this from?

 

by: jsvb1977Posted on 2009-10-29 at 11:42:28ID: 25696804

BlueDevilFan,

Sorry for not being more clear. We recently installed an application called PlanetPress. It handles form overlays, printing, and faxing of forms and documents. One feature of the application is the ability to run embedded vb scripts OR calling an external vb script.

There is one processes I am working on which requires me to monitor a directory for a file. when that file exists i need to continue on with the planet press process. when the file does not exist i need the planet press process to wait until file does exist. The vb script we are working on will handle this.

I didnt realize that using wscript would be a problem. I think the wscript.sleep is the issue as some wscript functions appear to work.?.?.?

Jason

 

by: egl1044Posted on 2009-10-29 at 12:37:59ID: 25697417

Add this below the (Set FSO = ) line. The link you posted seems to indicate you need explicitly create the object if from outside resource. Give that a try.

Set WScript = CreateObject("WScript.Shell")

 

by: egl1044Posted on 2009-10-29 at 13:39:58ID: 25698008

Ahh I see your problem the application is probrably using microsoft scripting control. You can use the Wscript objects but the core methods like Sleep() don't exists only the specific objects like Shell,Network etc.. This means you will need to either create an ActiveX.DLL and implement the Sleep() API in there and use CreateObject() on your ActiveX.dll. You could probrably use the Timer object to create a custom sleep as well.

 

by: jsvb1977Posted on 2009-10-29 at 13:47:37ID: 25698092

yep, i think you are correct. i also thought of something else....

I should be watching to see if the file has completed being written. i mean, i cant continue with the planet press process unless the file has completed being written to the file path.

know what i mean?

what do you recommend that i do?

As a work around i am using this script to act as a delay timer. it is a hack but is working. it will fail if a file takes longer than 6 seconds to be exported and written to the file path specified in the script.

what do you think of this script? can we work with this in some way?

Jason

strFile= "C:\Scripts\JRSTEST.txt"
strDelay= 5
set objFSO = createobject("Scripting.FileSystemObject")
 
if objFSO.FileExists(strFile) then
	msgbox "File Does Exist"
	'Do Nothing
else
	strResume = Second(now()) + strDelay
	Do until Second(Now()) > strResume
    Loop        
	msgbox "Sorry, the file does not exist"
    
end if

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: egl1044Posted on 2009-10-29 at 14:58:11ID: 25698674

Well you can only do this from scripting if the file will be a static size like 1024 bytes. Otherwise you will need to create another loop and check if additional bytes are still being written to that file. This is especially the case if the application writing to the file gives share access. However if the application writing to the file gives no access you could check for runtime error and this will only work if the application closes the handle immediatley after it finishes writing. It will be hard to come up with any kind of solution without knowing any information about the file.

 

by: jsvb1977Posted on 2009-10-29 at 15:21:35ID: 25698839

We figured out a way to do this with in the Planet Press application == so this script is no longer needed. i will award points to the one script that did the job OUTSIDE of planet press since it was the closest.

thanks to all that assisted!

Jason

 

by: jsvb1977Posted on 2009-10-29 at 15:22:44ID: 31647778

Many posted solutions would have worked to a degree, but this was the first complete solution posted.

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...