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

154 views Asked by At

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 :)

2

There are 2 answers

4
Mike67 On BEST ANSWER

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 :)

0
Hackoo On

Just to give you an idea , I share with you an old HTA named File_Search.hta from an old forum.

<html>
 <head>
 <title>File Search</title>
 <HTA:APPLICATION
 Application ID = "SearchFiles"
 APPLICATIONNAME = "File Search"
 BORDER = "Dialog"
 BORDERSTYLE = "Normal"
 CAPTION = "Yes"
 CONTEXTMENU = "Yes"
 ICON = ""
 INNERBORDER = "Yes"
 MAXIMIZEBUTTON = "Yes"
 MINIMIZEBUTTON = "Yes"
 NAVIGABLE = "No"
 SCROLL = "Auto"
 SCROLLFLAT = "No"
 SELECTION = "No"
 SHOWINTASKBAR = "Yes"
 SINGLEINSTANCE = "No"
 SYSMENU = "Yes"
 VERSION = "1.0"
 WINDOWSTATE = "Normal"
 />
 </head>
 <style type="text/css">
    a:link {color: #F19105;}
    a:visited {color: #F19105;}
    a:active {color: #F19105;}
    a:hover {color: #FF9900;background-color: rgb(255, 255, 255);}
 </style>
 <script Language="VBScript">
 'http://www.visualbasicscript.com/Simple-file-search-hta-m45254.aspx
 Option Explicit
 Dim iTimer
 Sub BrowseForFolder
    Dim objShell, objFolder, objFolderItem, strBrowsePath

    ' define constants for Shell.Application object
    Const WINDOW_HANDLE = 0
    Const NO_OPTIONS = 0

    Set objShell = CreateObject("Shell.Application") ' Create Shell.Application object
    Set objFolder = objShell.BrowseForFolder(WINDOW_HANDLE, "Choose map:",NO_OPTIONS) ' open file browser
    If objFolder Is Nothing Then Exit Sub
    Set objFolderItem = objFolder.Self
    strBrowsePath = CStr(objFolderItem.Path) ' assign path retrieved
    txtPath.value = strBrowsePath ' copy path to input box
 End Sub

 Sub start
    Dim strInput  :  strInput = txtSearch.value

    If strInput = "" Then
        DataArea.InnerHTML = "Nothing to do."
        Exit Sub ' exit sub if no keyword is specified
    Else
        DataArea.InnerHTML = "Busy searching..." ' update HTML body with message
        iTimer = window.setInterval("Search", 1000) 'wait 1 second to ensure message is displayed
        Search
    End If
 End Sub

 Sub Search
    Dim objFSO, strSearchpath, objFolderSearching, strHTML, intCount

    intCount = 0
    window.clearInterval(iTimer) ' clear iTimer
    strSearchpath = txtPath.value ' get value from input box

    Set objFSO = CreateObject("scripting.filesystemobject") ' create filesystemobject
    If objFSO.FolderExists(strSearchpath) = True Then
        Set objFolderSearching = objFSO.GetFolder(strSearchpath) ' get folder if it exists
    Else
        ' give error if path is invalid and exit sub
        MsgBox "Path not found. " & vbCrLf & strSearchpath,vbExclamation,"Path"
        DataArea.InnerHTML = "Try again."
        Set objFSO = Nothing
        txtPath.Select
        Exit Sub
    End If

    ' begin building table with results
    strHTML = "Results [[COUNT] File(s) Found]: <br><br>" & _
              "<table border='1' style='border-collapse: collapse; font size:9pt' bordercolor='#CCCCCC' width='100%' id='Table1'>" & _
              "<tr><td><strong>Name</strong></td><td><strong>Path</strong></td>" & _
              "<td><strong>Size</strong></td><td><strong>Type</strong></td>" & _
              "<td><strong>Modified</strong></td><td><strong>Accessed</strong></td></tr>"
    CheckFolder objFolderSearching, strHTML, intCount
    strHTML = strHTML & "</table>" ' call CheckFolder Function to continue building table w/ file(s) data
    strHTML = Replace(strHTML, "[COUNT]", intCount)
    DataArea.InnerHTML = strHTML ' display table
    txtSearch.select
    Set objFSO = Nothing
    Set objFolderSearching = Nothing
 End Sub

 Sub CheckFolder(objCurrentFolder, ByRef strHTML, ByRef intCount)
    Dim strSearch, objFile, strTemp, strFileName, ParentFolder, strFilePath, strFileSize
    Dim strFileType, strFileModified, strFileAccess, objNewFolder

    strSearch = UCase(txtSearch.value) ' get value from input box

    For Each objFile In objCurrentFolder.Files ' get files in folder
        On Error Resume Next
        strTemp = UCase(CStr(objFile.Name))
        If InStr(1, strTemp, strSearch, 1) <> 0 Then ' if file name matches keyword then build table
            'Got one
            intCount = intCount + 1
            strFileName = objFile.Name
            ParentFolder = objFile.ParentFolder
            strFilePath = objFile.Path
            strFileSize = FormatNumber((objFile.Size/1024),2) + " Kb"
            strFileType = objFile.Type
            strFileModified = objFile.DateLastModified
            strFileAccess = objFile.DateLastAccessed
            '"<a href=""#"" OnClick='Explore("""& Explore(strFilePath) & """)'>"& objProcess.Name &"</a>"
            strHTML = strHTML & "<tr><a href=""#"" OnClick='Explore("""& strFilePath & """)'><td>" & strFileName & "</a></td><td>" &_
            "<a href=""#"" OnClick='Explore("""& ParentFolder & """)'>" & _
                                ParentFolder & "</a></td><td>" & strFileSize & "</td>" & _
                                "<td>" & strFileType & "</td><td>" & strFileModified & "</td>" & _
                                "<td>" & strFileAccess & "</td></tr>"
        End If
        On Error GoTo 0
    Next

    For Each objNewFolder In objCurrentFolder.subFolders ' get subfolders for recursion
        On Error Resume Next
        CheckFolder objNewFolder, strHTML, intCount
        On Error GoTo 0
    Next
 End Sub

 Sub StartOnEnter
    If window.event.keyCode = 13 Then ' if the Enter key is pressed, then call the Start sub
        Start
    End If
 End Sub

 Function Explore(filename)
    Dim ws,Result
    set ws = CreateObject("wscript.shell")
    Result = ws.run("Explorer /n,/select,"& filename &"")
    Explore = Result
End Function

 </script>
 <body onKeyPress="StartOnEnter" STYLE="overflow:auto;font:arial; color:#000000; filter:progid:DXImageTransform.Microsoft.Gradient (GradientType=0, StartColorStr='#FFFFFF', EndColorStr='#CCCCCC')">
 <basefont SIZE="2">
 Search for:<BR>
 <input type="text" style="background-color:#ffffff" size="40" name="txtSearch" value="">
 in&nbsp
 <input type="text" style="background-color:#ffffff" size="25" name="txtPath" value="C:\">
 <input id=runbutton class="button" type="button" value=" ... " name="brows_button"  onClick="BrowseForFolder"><p>
 <input id=runbutton STYLE="filter:progid:DXImageTransform.Microsoft.Gradient (GradientType=1, StartColorStr='#0575F1', EndColorStr='#A4C8EF')" class="button" type="button" value=" Search " name="run_button"  onClick="Start"><p>
 <span id="DataArea"></span>
 </basefont>
 </body>
 </html>