Vbscript - Compare and copy files from folder if newer than destination files

31,040

Solution 1

Your algorithm looks good. Practically speaking, you would need to get the Files using a FileSystemObject, and retrieve their respective DateLastModified properties. You can do a DateDiff on the two dates to compare which is earlier.

Slightly modified examples from DevGuru:

Dim filesys,demofile, date1, date2
Set filesys = CreateObject("Scripting.FileSystemObject")
Set demofile = filesys.GetFile("filename1")
date1 = demofile.DateLastModified
demofile = filesys.GetFile("filename2")
date2 = demofile.DateLastModified

If DateDiff("d", date1, date2) > 0 Then
    'date2 is more recent than date1, comparison by "day" ' ** Improvement **
End If

Edit: Misspelled the URL.


Improvement In the comment, "date1" and "date2" have been exchanged. The MSDN document says: If date1 refers to a later time than date2, the DateDiff function returns a negative number. http://msdn.microsoft.com/en-us/library/xhtyw595(v=vs.84).aspx

Solution 2

Your code looks reasonable. Just look out for readonly files and such.

You can use the FileSystemObject to do the actual file operations, just look at:

http://msdn.microsoft.com/en-us/library/6kxy1a51%28VS.85%29.aspx

Share:
31,040
Kenny Bones
Author by

Kenny Bones

Updated on July 18, 2020

Comments

  • Kenny Bones
    Kenny Bones almost 4 years

    I'm trying to design this script that's supposed to be used as a part of a logon script for alot of users. And this script is basically supposed to take a source folder and destination folder as basically just make sure that the destination folder has the exact same content as the source folder. But only copy if the datemodified stamp of the source file is newer than the destination file.

    I have been thinking out this basic pseudo code, just trying to make sure this is valid and solid basically.

    Dim strSourceFolder, strDestFolder
    strSourceFolder = "C:\Users\User\SourceFolder\"
    strDestFolder = "C:\Users\User\DestFolder\"
    
    For each file in StrSourceFolder
         ReplaceIfNewer (file, strDestFolder)
    Next
    
    Sub ReplaceIfNewer (SourceFile, DestFolder)
    
        Dim DateModifiedSourceFile, DateModifiedDestFile
        DateModifiedSourceFile = SourceFile.DateModified()
        DateModifiedDestFile = DestFolder & "\" & SourceFile.DateModified()
    
        If DateModifiedSourceFile < DateModifiedDestFile
            Copy SourceFile to SourceFolder
        End if
    
    End Sub
    

    Would this work? I'm not quite sure how it can be done, but I could probably spend all day figuring it out. But the people here are generally so amazingly smart that with your help it would take alot less time :)

  • Kenny Bones
    Kenny Bones about 14 years
    This looks very promising :) I'm gonna try it out :)