Using VBScript to find most recent file date in a single folder

mikeclemson picture mikeclemson · Feb 9, 2012 · Viewed 55.6k times · Source

How could I modify this VBScript to return only the newest file's name and Last Modified date? Currently it returns anything modified in the last 24 hours. I want to look for the most recent file only. I borrowed this from StackOverflow, not yet a VBScript wizard.

option explicit  
dim fileSystem, folder, file
dim path   
path = "C:\test"  
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 

Answer

Stephen Quan picture Stephen Quan · Feb 9, 2012

The following implements GetRecentFile (and GetRecentFolder) and includes sample usage:

Option Explicit  

Function GetRecentFile(path)
  Dim fso, file
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set GetRecentFile = Nothing
  For Each file in fso.GetFolder(path).Files
    If GetRecentFile is Nothing Then
      Set GetRecentFile = file
    ElseIf file.DateLastModified > GetRecentFile.DateLastModified Then
      Set GetRecentFile = file
    End If
  Next
End Function

Function GetRecentFolder(path)
  Dim fso, folder
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set GetRecentFolder = Nothing
  For Each folder in fso.GetFolder(path).SubFolders
    If GetRecentFolder is Nothing Then
      Set GetRecentFolder = folder
    ElseIf folder.DateLastModified > GetRecentFolder.DateLastModified Then
      Set GetRecentFolder = folder
    End If
  Next
End Function

Dim recentFile
Set recentFile = GetRecentFolder("C:\Temp")
If recentFile is Nothing Then
  WScript.Echo "No recent files found"
Else
  WScript.Echo "Recent file is " & recentFile.Name & " " & recentFile.DateLastModified
End If