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

10,120

Solution 1

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

Solution 2

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
Share:
10,120
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

  • Admin
    Admin about 14 years
    Also, what exactly does "option explicit" do?
  • and_the_rand
    and_the_rand about 14 years
    It requires that you declare your variables.