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

Kenny Bones picture Kenny Bones · May 14, 2010 · Viewed 31.1k times · Source

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 :)

Answer

Mirkules picture Mirkules · May 14, 2010

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