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
For working with files on VBScript
it is recommended you use the FileSystemObject
.
The FileSystemObject
has the following feature's that help you solve your problem:
FileSystemObject.GetFolder
- Returns a Folder object corresponding to the folder in a specified path.Folder.Files
- Returns a Files collection consisting of all File objects contained in the specified folder.File.DateLastModified
- Returns the date and time that the specified file or folder was last modified.To demonstrate, I have supplied an implementation of GetRecentFile
(and GetRecentFolder
) which scans the supplied input path and determines the most recent file by finding the file that has the greatest DateLastModified
property.
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
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With