loopsvbscripthtafile-existswscript.shell

Keep searching for file and once it is there just open it


So, I have the following code

FileName = "Path\To\FileName"
Set FSO = CreateObject("Scripting.FileSystemObject")
Do
   If FSO.FileExists(FileName) Then 
       FSO.DeleteFile FileName
   End If
   WScript.Sleep 1000
Loop

It looks for a specific file over and over again and once it is found it is deleted.

I want to modify it, I want this script to look for file over and over again and once it is found I just want to open that text file and stop the execution of the script.

Looking forward to your help :)


Solution

  • Use the WScript.Shell object to launch a file or application in VBScript.

    FileName = "c:\tmp\newfile.txt"
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Do
       If FSO.FileExists(FileName) Then 
           With CreateObject("WScript.Shell")
              .Run FileName ' or .Run "notepad.exe " & FileName
           End With
           Wscript.Quit
       End If
       WScript.Sleep 1000
    Loop
    

    For an HTA application, you need to use setTimeOut for the 'loop'

    <script language="VBScript">
    
    Sub CheckFile
       FileName = "c:\tmp\newfile.txt"
       Set FSO = CreateObject("Scripting.FileSystemObject")
       If FSO.FileExists(FileName) Then 
           With CreateObject("Shell.Application")
              .ShellExecute FileName, FileName, , , NORMAL_WINDOW ' or .ShellExecute "Notepad.exe", FileName,...
           End With
           Self.Close()  'exit app
       End If
       window.setTimeOut "CheckFile", 1000  'wait 1 second, then recheck
    End Sub
    
    CheckFile  'first check
    
    </script>
    

    Thanks to Hackoo for getting me on the right track :)