3

With this VBScript code I was able to copy files. If the file exists it does nothing, if not it will copy the files needed.

Dim Photo
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")

For Each Photo In ObjPhoto.GetFolder( SourceFolder).Files
    If Not ObjPhoto.FileExists(ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))) Then
        photo.Copy ObjPhoto.BuildPath(DistinationFolder, Photo.Name), True
    End If
Next

I want to compare the files if the source files also exists in the destination folder and replace it by the newer.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
nater303
  • 85
  • 2
  • 14
  • visit following forum hope this will help: http://www.vbforums.com/showthread.php?621051-Compare-files-in-two-folders – saqibahmad May 29 '15 at 13:09

1 Answers1

1

If you want to overwrite based on the last modified date, then the File object has the property you want: DateLastModified. (You can check all properties of the File object here.)

You already have access to the source file objects (your code's Photo variable) so you just need to get the target's file object.

Something like this should work:

Dim Photo
Dim targetFile, bmpTargetFilename, jpgTargetFilename

SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"

Set ObjPhoto = CreateObject("Scripting.FileSystemObject")

For Each Photo In ObjPhoto.GetFolder(SourceFolder).Files
    bmpTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))
    jpgTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Photo.Name)

    If ObjPhoto.FileExists(bmpTargetFilename) Then
        ' Get the target file object
        Set targetFile = ObjPhoto.GetFile(jpgTargetFilename)
        ' Now compare the last modified dates of both files
        If Photo.DateLastModified > targetFile.DateLastModified Then
            Photo.Copy jpgTargetFilename, True
        End If
    Else
        Photo.Copy jpgTargetFilename, True
    End If
Next

A couple of notes:

  • It seems you are checking for the existence of a .BMP file yet copying a .JPG file, so I made it explicit by using two variables.
  • I am also assuming you want to compare the JPG files, since those are the ones being copied.
ssarabando
  • 3,397
  • 2
  • 36
  • 42