VB script - search for a file in directory

Kiwi picture Kiwi · Apr 17, 2013 · Viewed 45.3k times · Source

I am trying to write a VB script (having never attempted before) - I need it to search the folder'\file001\source$' - whilst in the folder search for all 'Update.exe'files - If this is done manually, in Windows it takes a long long time! I would like all the files that it finds with this name - to be copied into a new folder.

Looking at various help forums I am getting more and more confused.

Below is what I have attempted:

Set fso = CreateObject("Scripting.FileSystemObject")
ShowSubfolders fso.GetFolder("\\file001\source$")

'foldername = "\file001\source$" 'filename = "Updater.exe"

Function ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
        Wscript.Echo Subfolder.Path
        ShowSubFolders Subfolder
    Next
End Function

This is to search through a folder, recursively through the folders sub folders to find all files with this name.

I have also done research into -directory.getfiles. But have no clue if this is the right direction.

As a newbie to VB script, I have researched and attempted to play around with vb script, to get the function I desire. I would be grateful to any help I can get.

Again - my target is to - find all files within the given folder and subfolders with the name update.exe - and then to copy these files found into a new folder. Thank you in advance.

Answer

Ansgar Wiechers picture Ansgar Wiechers · Apr 17, 2013

If you only want to check the content of a single folder for the existence of a particular file you can do that like this:

Set fso = CreateObject("Scripting.FileSystemObject")

foldername = "\\file001\source$"
filename   = "Update.exe"

If fso.FileExists(fso.BuildPath(foldername, filename)) Then
  WScript.Echo filename & " exists."
End If

If you want to check the subfolders of foldername as well, you need to recurse into subfolders with something like this. You can either integrate the check from the above code sample in the loop over the subfolders, or add another loop over the files in the folder:

Set fso = CreateObject("Scripting.FileSystemObject")

CopyUpdater fso.GetFolder("\\file001\source$")

Sub CopyUpdater(fldr)
  For Each f In fldr.Files
    If LCase(f.Name) = "update.exe" Then
      'copy file to somewhere else
    End If
  Next

  For Each sf In fldr.SubFolders
    CopyUpdater sf
  Next
End Sub