?
Solved

FileSystemObject.FindFile?  Script?

Posted on 2003-03-02
6
Medium Priority
?
357 Views
Last Modified: 2007-12-19
I want to create a simple VBS Script that will find a File that I know is in the drive (but do not know exactly where) and put it in the C:\TempFolder, for example, a "wishful thinking" script would be:
--------------------------------------------------
Dim fileword
Set fileword=CreateObject("Scripting.FileSystemObject")

fileword.FINDFILE ("winword.exe")

fileword.MoveFile "From whereever it is - WINWORD.EXE", "c:\TempFolder\"  
---------------------------------------------------
Of course the program won't work, but with that in mind maybe someone can help me re-script.

0
Comment
Question by:matwiz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 5

Accepted Solution

by:
Cimperiali earned 60 total points
ID: 8053313
Recursive search to find a file. It will recursively search thorughut your drive. You can implement this to searchtrough many drives...

Option Explicit

Dim fso  'Scripting.FileSystemObject
Dim theFolder  'Scripting.Folder
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFolder = fso.GetFolder("C:\")
Dim theResult
theResult = searchIt(theFolder, "winword.exe")
MsgBox theResult
Set theFolder = Nothing
Set fso = Nothing
End Sub

Private Function searchIt(theStartPath, TheFileName)
   Dim localF  'Scripting.File
   Dim subDir 'Scripting.Folder
   
   On Error Resume Next
   For Each localF In theStartPath.Files
   
      If LCase(localF.Name) = LCase(TheFileName) Then
         If Err.Number = 0 Then
            searchIt = localF.Path
            Exit Function
          Else
            Err.Clear
          End If
      End If
   Next
   For Each subDir In theStartPath.SubFolders
      searchIt = searchIt(subDir, TheFileName)
      If searchIt <> "" Then
         Exit Function
      End If
   Next
End Function



0
 
LVL 1

Expert Comment

by:Mirx
ID: 8053388
Hi, sorry to sort of repeat the same thing, but the previous suggestion was submitted while I was working on my post. Anyway, here goes:

Call folderlist("C:\", "winword.exe", "C:\TempFolder")

sub folderlist(searchFolder,toFind, destDir)

     On Error Resume Next
     Set fso = CreateObject("Scripting.FileSystemObject")

     Dim myFolder,Subfolder,mySubfolders, File, tmpFileName

     If (Right(searchFolder,1) <> "\") Then
          searchFolder = searchFolder & "\"
        End If

     Set myFolder = fso.GetFolder(searchFolder)
     Set mySubFolders = myFolder.SubFolders

        For each File in MyFolder.Files   'Loop trough the files in the folder
          'WScript.Echo ("File: '" & File.Name & "'")
          toFind = LCase(toFind)
          tmpFileName = LCase(File.Name)
          if (tmpFileName = toFind) then

             WScript.Echo (Left(file.path, Len(file.path) - Len(file.name) )   )
             WScript.Echo (File.Size & " bytes" & vbtab & File.Type & vbtab & File.DateCreated & vbtab & File.name )

             If (Right(destDir,1) <> "\") Then
               destDir = destDir & "\"
             End If

             if fso.FileExists(destDir & file.name) Then
               WScript.Echo destDir & file.name & " already exists."
             Else
               WScript.Echo ("fso.CopyFile " & File.path & ", " & destDir)
               fso.CopyFile File.path, destDir
             End If

             If (Err.Number <> 0) Then
               WScript.Echo ("Error: " & Err.Number & vbcrlf & Err.Description & vbcrlf & Err.Source)
             End if
          End If
        Next

     For each Subfolder in myFolder.SubFolders

          'WScript.Echo ("Subfolder: " & Subfolder.Name)
          Call folderlist(Subfolder.path, toFind, destDir)
     Next
end sub
0
 
LVL 9

Expert Comment

by:mcallarse
ID: 8054459
Here's a slightly different take, relying on the Windows Dir command as opposed to recursion. Performance benefit should be significant.

[End of 20-point answer]

Copy-and-paste the following into a vbs file, and execute. FindFile parameters are:

strFind - Name of the file to find. Wildcards can be used.
strDest - Location to copy files to.
StartIn - Location to start search in. Pass an empty string to have Sub search all local drives.

--

Call FindFile("winword.exe", "C:\Temp\","C:\Temp")

Sub FindFile(strFind, ByVal strDest, StartIn)

Dim fso, ts
Dim sh

Const TemporaryFolder = 2

Dim fldrTemp
Dim strBat, strLog

Set fso = CreateObject("Scripting.FileSystemObject")

With fso

'   Verify Destination and Starting (if applicable) folders exist.
    If Not .FolderExists(strDest) Then
        Wscript.Echo "Destination folder does not exist."
     Set fso = Nothing
     Exit Sub
    ElseIf Not StartIn = Empty And Not .FolderExists(StartIn) Then
        Wscript.Echo "Starting folder does not exist."
     Set fso = Nothing
     Exit Sub
    End If
    strDest = .GetFolder(strDest).Path

'   Create temporary file names.
    fldrTemp = .GetSpecialFolder(TemporaryFolder).Path & "\"
    strBat = fldrTemp & "_FindFile.bat"
    strLog = fldrTemp & "_FindFile.log"
   
'   Create batch file.
    Set ts = fso.CreateTextFile(strBat, True)
    If .FileExists(strLog) Then .DeleteFile strLog, True
    If StartIn = Empty Then
     Dim drv
        For Each drv In .Drives
            If drv.DriveType = Fixed Then
                cmd = "dir """ & drv & "\" & strFind & """ /b /s >> " & strLog
                ts.WriteLine cmd
            End If
        Next
    Else
        cmd = "dir """ & .GetFolder(StartIn).Path & "\" & strFind & """ /b /s >> " & 

strLog
        ts.WriteLine cmd
    End If
    ts.Close
   
'   Execute batch file.

    set sh = CreateObject("WScript.Shell")
    sh.Run strBat, 7, True
    .DeleteFile strBat, True
   
'   Process results. Copy file(s) to new Destination folder.
    Set ts = .OpenTextFile(strLog)
    If ts.AtEndOfStream Then
     Wscript.Echo "No files found!"
    End If
    Dim myFile, intButton
    Do Until ts.AtEndOfStream
     myFile = ts.ReadLine
     If .FileExists(strDest & "\" & .GetFile(myFile).Name) Then
         intButton = sh.Popup("File exists in destination folder.

Overwrite?",,myFile,4)
     Else: intButton = 6 ' Yes
     End If
        If intButton = 6 Then .CopyFile myFile, .GetFolder(strDest) & "\"
    Loop
    ts.Close
    .DeleteFile strLog, True
End With

Set sh = Nothing
Set fso = Nothing: Set ts = Nothing: Set drv = Nothing

End Sub
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:mcallarse
ID: 8054487
Add the following line to the Sub Declarations section.

Const Fixed = 2
0
 

Expert Comment

by:CleanupPing
ID: 8900900
matwiz:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
Experts: Post your closing recommendations!  Who deserves points here?
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 9012066
Moderator, my recommended disposition is:

    Accept Cimperiali's comment(s) as an answer.

DanRollins -- EE database cleanup volunteer
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question