Search code examples
vbscriptcopyletters

Vbscript copy files based on beginning letters


I am trying to get this script to copy all files starting with "XX". Currently it only copies one file.

Dim objFSO, colFiles, objFile, strDestFolder, objNewestFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colFiles = objFSO.GetFolder("C:\source")
strDestFolder = "C:\destination\"

For Each objFile In colFiles.Files
  If Left(objFile.Name, 2) = "XX" Then
  If objNewestFile = "" Then   
    Set objNewestFile = objFile  
  Else   
      If objNewestFile.DateLastModified < objFile.DateLastModified Then    
        Set objNewestFile = objFile   
      End If  
  End If
End If
Next

If Not objNewestFile Is Nothing Then 
objFSO.CopyFile objNewestFile.Path,strDestFolder,True
End If

WScript.Echo "Copied."    

Solution

  • You can use wildcards * and ? in [source] argument of FSO .CopyFile method.

    So the code may look like:

    Dim objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.CopyFile "C:\source\XX*.*", "C:\destination\", True
    WScript.Echo "Copied."