Jimminy
Jimminy

Reputation:

Can VBScript determine the most recently modified (or added) file in a particular folder?

I have a script (or more accurately WILL have a script) that checks a folder and copies a file from this folder to a different location (will run once per day). The fileName that I'd like to copy from, however, changes based on the date.

Basically, instead of setting the "strFilePath" to "C:\somePath\somePath2\myFile.txt" I would like to simply take the most recently modified (or added - does this make a difference in terms of the script??) in the "somePath2" folder and copy it to the destination.

Bonus (but not completely necessary) would be to check in the script if the file was modified/added in the last 24 hours and only copy it over in that case.

Upvotes: 2

Views: 10499

Answers (2)

Fionnuala
Fionnuala

Reputation: 91326

How about:

Dim f, fl, fs 
Dim filedate, filename

Set fs = CreateObject("Scripting.FileSystemObject")
Set fl = fs.GetFolder("C:\Docs")

For Each f In fl.Files
    If IsNull(filedate) Or f.DateCreated > filedate Then
        filedate = f.DateCreated
        filename = f.Name
    End If
Next

''Most recent file and date are contained in filename, filedate

Upvotes: 3

Austin Salonen
Austin Salonen

Reputation: 50215

Give this a try:

option explicit

dim fileSystem, folder, file
dim path 

path = "C:\temp"

Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(path)

for each file in folder.Files    
    if file.DateLastModified > dateadd("h", -24, Now) then
        'whatever you want to do to process'
        WScript.Echo file.Name & " last modified at " & file.DateLastModified
    end if
next

Upvotes: 5

Related Questions