Link to home
Start Free TrialLog in
Avatar of Frosty555
Frosty555Flag for Canada

asked on

vbscript to check age of newest file

I'm looking for a vbscript example of how to enumerate the files in a folder which matches a certain mask (e.g backup*.zip) find the newest one, and determine how old it is in days (e.g 2 days old). There's a number of complexities I'm not sure of how to do in VBScript.
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Try this:
Option Explicit

Dim oFS, oFolder, oFile, dNewest, sFilename
Set oFS = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFS.GetFolder("D:\temp")
For Each oFile In oFolder.Files
 If oFile.DateLastModified > dNewest Then
  dNewest = oFile.DateLastModified
  sFilename = oFile.Name
 End If
Next
Set oFolder = Nothing

MsgBox "File: " & sFilename & ", date: " & dNewest & ", " & DateDiff("d", Date(), dNewest) & " days old"

Open in new window

robert_schutt,

The difficulties arise with the file mask ;-). There needs to be a file filter, or manual check for fitting file names.
oops forgot the filename match. Will be back in a minute.
Avatar of madhatter550
madhatter550

How about this

set oFolder=createobject("scripting.filesystemobject").GetFolder("C:\test")

For Each File In oFolder.Files
	If LCase(Left(File.Name, 6)) = "backup" Then
		If LCase(Right(File.Name, 4)) = ".zip" Then
		    If NBackup = "" Then
		        Set NBackup = File
		    Else
		        If NBackup.DateCreated < File.DateCreated Then
		            Set NBackup = File
		        End If
		    End If
		End If
	End If
Next

Msgbox NBackup.Name & vbTab & DateDiff("d", Date(), NBackup.datecreated) & " Days Old"

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Qlemo, yeah realized that after posting, took me longer than a minute because I wanted to use the original requested mask and make it easily configurable

@Frosty555 note the other main difference between @madhatter550's script and mine is using the creation date versus the last modification date to determine the age of a file
Avatar of Frosty555

ASKER

The regex is a nice touch... that was the main thing I didn't know how to do since FileSystemObject doesn't actually support "masks".