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

I am trying to create this script that should be used as part of a login script for many users. And this script basically has to take the source folder and the destination folder as basically just make sure the destination folder has the same content as the source folder. But copy only if the datemodified stamp of the source file is newer than the destination file.

I thought about this basic pseudocode, just trying to make sure it was valid and solid.

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

      

Will this work? I'm not really sure how this can be done, but I could possibly spend all day doing this. But the people here are usually so amazingly smart that it will take a lot less time with your help :)

+2


a source to share


2 answers


Your algorithm looks good. In practice, you will need to get the files using the FileSystemObject and get their corresponding DateLastModified properties. You can do DateDiff for two dates for comparison that was before.

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: with a URL error.


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

+2


a source


Your code looks sane. Just pay attention to readonly files etc.

You can use FileSystemObject

to do actual file operations, just look at:



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

+1


a source







All Articles