Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

VBScript - Find the latest file in a folder

5,779 views
Skip to first unread message

FinalZero

unread,
Aug 4, 2005, 12:37:43 PM8/4/05
to
Hi,

Need some help, I am going completely mad trying to perform a simple
task with VBScript.

I have put together a simple enough script which scans a specific
location, iterates through any subfolder in the directory and then
scans each folder for files.

What it should be doing is scanning the files, finding the latest file
and checking if:

1. The file matches the current system date
2. Is no more than four hours old

As I only need to see if log files are being written into the sub
folder I am thinking that I only need to check for the latest file and
make sure its for the current date, and then validate it against time
to see if its less than four hours old - if no files exist that are
less than four hours old the script raises an alert (wrote an error
handling class that simply sends an email to the support guys).

I have tried all sorts of things, sorts, using multiple arrays to do
swapping etc but am having no luck. I tried using a simple bubblesort
routine from Microsoft's site - worked great for single dimension
arrays (I was storing file dates in the array) however when I tried
adding the file names to go with the date the bubblesort fell on its
backside as I realized VBScript cannot redimm multidimensional arrays.

I have all of the code built (WSF file) up to the point I am able scan
the sub folders, get a list of the files in the sub folder, get their
attributes into an array but then I am stuck - at this point I need to
find out which file is the latest file and check its time.

Thanks in advance, I hope someone can bring back my sanity ;-)

Cheers,

TK

Torgeir Bakken (MVP)

unread,
Aug 4, 2005, 1:39:05 PM8/4/05
to
FinalZero wrote:

> Hi,
>
> Need some help, I am going completely mad trying to perform a simple
> task with VBScript.
>
> I have put together a simple enough script which scans a specific
> location, iterates through any subfolder in the directory and then
> scans each folder for files.
>
> What it should be doing is scanning the files, finding the latest file
> and checking if:
>
> 1. The file matches the current system date
> 2. Is no more than four hours old
>
> As I only need to see if log files are being written into the sub
> folder I am thinking that I only need to check for the latest file and
> make sure its for the current date, and then validate it against time
> to see if its less than four hours old - if no files exist that are
> less than four hours old the script raises an alert (wrote an error
> handling class that simply sends an email to the support guys).
>

> (snip)
Hi,

Here you go:

'--------------------8<----------------------

sPath = "c:\my test"


Set oFSO = CreateObject("Scripting.FileSystemObject")

sNewestFile = GetNewestFile(sPath)

If sNewestFile <> "" Then

WScript.Echo "Newest file is " & sNewestFile

dFileModDate = oFSO.GetFile(sNewestFile).DateLastModified
If DateDiff("h", dFileModDate, Now) > 4 Then
MsgBox "File is older than 4 hours, send an e-mail!"
End If

Else
WScript.Echo "Directory is empty"
End If


Function GetNewestFile(ByVal sPath)

sNewestFile = Null ' init value

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files

' enumerate the files in the folder, finding the newest file
For Each oFile In oFiles
On Error Resume Next
If IsNull(sNewestFile) Then
sNewestFile = oFile.Path
dPrevDate = oFile.DateLastModified
Elseif dPrevDate < oFile.DateLastModified Then
sNewestFile = oFile.Path
End If
On Error Goto 0
Next

If IsNull(sNewestFile) Then sNewestFile = ""

GetNewestFile = sNewestFile

End Function

'--------------------8<----------------------

--
torgeir, Microsoft MVP Scripting and WMI, Porsgrunn Norway
Administration scripting examples and an ONLINE version of
the 1328 page Scripting Guide:
http://www.microsoft.com/technet/scriptcenter/default.mspx

FinalZero

unread,
Aug 5, 2005, 10:42:54 AM8/5/05
to
Torgeir,

Thankyou for the response, unfortunately I was unable to get the
results I expected from your code (however its given me some direction
as to what I should be doing).

For some reason the latest file is not recognised, instead the third
newest file is picked up, any ideas?

Cheers,

Tahir

FinalZero

unread,
Aug 5, 2005, 10:53:32 AM8/5/05
to
Hi Torgeir,

Thank you for the help, unfortunately I could not get the results I
wanted. The code you gave me seems to pick up the third from newest
file, not sure why..

However your code has given me some ideas as to what I should be doing
so I will try to hack something together - in the meantime if you can
see whats wrong then I would be grateful.

As an example the folder the script is scanning contains about 12 files
(e.g LOGFILE0001_1, LOGFILE0001_2 etc). Half the files are dated for
the previous date and the other half for the current date (well should
be) so the script should only test files for todays date and then check
which are out of date, which are zero bytes (I got code to do this)
etc.

I am using the following code to test only files for todays date:

FileDate = DatePart("D",File.DateLastModified) & "/" &
DatePart("M",File.DateLastModified) & "/" &
DatePart("YYYY",File.DateLastModified)
LocalDate = DatePart("D",sDate) & "/" & DatePart("M",sDate) & "/"
& DatePart("YYYY",sDate)
if FileDate = LocalDate then

Thanks in advance,

Tahir

Torgeir Bakken (MVP)

unread,
Aug 5, 2005, 11:37:33 AM8/5/05
to
FinalZero wrote:

> Hi Torgeir,
>
> Thank you for the help, unfortunately I could not get the results I
> wanted. The code you gave me seems to pick up the third from newest
> file, not sure why..

I deleted a line in my code by mistake before posting, that is what
causes this. Below is a corrected version that will work better (see
comment "' This is the line missing previously:" for the added line).

I also changed the code to look for 240 minutes instead of 4 hours
to get a better "resolution" on the time interval.

So


If DateDiff("h", dFileModDate, Now) > 4 Then

is changed to
If DateDiff("n", dFileModDate, Now) > 240 Then

Try this one (see also further below in this post for another
script solution):

'--------------------8<----------------------

sPath = "c:\my test"


Set oFSO = CreateObject("Scripting.FileSystemObject")

sNewestFile = GetNewestFile(sPath)

If sNewestFile <> "" Then

WScript.Echo "Newest file is " & sNewestFile

dFileModDate = oFSO.GetFile(sNewestFile).DateLastModified
If DateDiff("n", dFileModDate, Now) > 240 Then


MsgBox "File is older than 4 hours, send an e-mail!"
End If

Else
WScript.Echo "Directory is empty"
End If


Function GetNewestFile(ByVal sPath)

sNewestFile = Null ' init value

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files

' enumerate the files in the folder, finding the newest file
For Each oFile In oFiles
On Error Resume Next
If IsNull(sNewestFile) Then
sNewestFile = oFile.Path
dPrevDate = oFile.DateLastModified
Elseif dPrevDate < oFile.DateLastModified Then
sNewestFile = oFile.Path

' This is the line missing previously:
dPrevDate = oFile.DateLastModified


End If
On Error Goto 0
Next

If IsNull(sNewestFile) Then sNewestFile = ""

GetNewestFile = sNewestFile

End Function

'--------------------8<----------------------

> However your code has given me some ideas as to what I should be doing


> so I will try to hack something together - in the meantime if you can
> see whats wrong then I would be grateful.
>
> As an example the folder the script is scanning contains about 12 files
> (e.g LOGFILE0001_1, LOGFILE0001_2 etc). Half the files are dated for
> the previous date and the other half for the current date (well should
> be) so the script should only test files for todays date and then check
> which are out of date, which are zero bytes (I got code to do this)
> etc.
>
> I am using the following code to test only files for todays date:
>
> FileDate = DatePart("D",File.DateLastModified) & "/" &
> DatePart("M",File.DateLastModified) & "/" &
> DatePart("YYYY",File.DateLastModified)
> LocalDate = DatePart("D",sDate) & "/" & DatePart("M",sDate) & "/"
> & DatePart("YYYY",sDate)
> if FileDate = LocalDate then
>
>

There is really no point in testing on todays date, just use
DateDiff("n", dFileModDate, Now) and see it if returns more or
less than 240 minutes (4 hours).

If you don't care about the file name of the newest updated file, and
you just want to test if one ore more files that have been updated
the last 240 minutes (4 hours), you can use this code instead of the
code I posted further up:


'--------------------8<----------------------

sPath = "c:\my test"

sPath = "c:\2"

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files

If oFiles.Count > 0 Then

' Enumerate the files in the folder looking for files updated
' within the last 4 hours. If such a file is found, exit the loop.
bolFileIsNewEnough = False ' init value


For Each oFile In oFiles
On Error Resume Next

dFileModDate = oFile.DateLastModified
If Err.Number = 0 Then
If DateDiff("n", dFileModDate, Now) < 240 Then
bolFileIsNewEnough = True
Exit For
End If
End If
Next
On Error Goto 0

If Not bolFileIsNewEnough Then
MsgBox "All files are older than 4 hours, send an e-mail!"
End if

Else
WScript.Echo "Directory is empty"
End If

'--------------------8<----------------------

Torgeir Bakken (MVP)

unread,
Aug 5, 2005, 11:40:52 AM8/5/05
to

I deleted a line in my code by mistake before posting, correction
further down in this post.


Torgeir Bakken (MVP) wrote:

' Oops, one line was missing
dPrevDate = oFile.DateLastModified

FinalZero

unread,
Aug 5, 2005, 12:24:22 PM8/5/05
to
Thanks dude, worked perfectly!

I will adapt the code into my script so it can search through
consecutive folders and then get the results into an Array (the array
is used to build the message body of the email alert and SNMP Trap).

Thanks again,

Tahir

bowlsys

unread,
Feb 15, 2006, 5:53:05 AM2/15/06
to

bowlsys wrote:
> *I have a need to find the latest file in a folder with a specific
> extension. But as a newbie to VBS , am unsure of how to modify the
> code *

--
bowlsys
------------------------------------------------------------------------
Posted via http://www.codecomments.com
------------------------------------------------------------------------

bowlsys

unread,
Feb 15, 2006, 5:52:07 AM2/15/06
to

FinalZero wrote:
> *Thanks dude, worked perfectly!
> Tahir *


I have a need to find the latest file in a folder with a specific
extension. But as a newbie to VBS , am unsure of how to modify the code

--

Alexander Mueller

unread,
Feb 20, 2006, 3:12:27 AM2/20/06
to bowlsys
bowlsys schrieb:

> bowlsys wrote:
>> *I have a need to find the latest file in a folder with a specific
>> extension. But as a newbie to VBS , am unsure of how to modify the
>> code *

Option Explicit
Const strDir = "<fully qualifed path to a local directory>"
Const strSearchedExt = "<extensionname>" 'extension without the dot


Dim fs, objDir, objFile
Dim datMax, objMostRecentFile
Dim strExt

'~~get fs-object
set fs = CreateObject ("scripting.filesystemobject")

'~~get folder
set objDir = fs.GetFolder(strDir)

'~~initialize with a pretty back-dated value
datMax = CDate(0)

'~~initialize with empty obj-reference
Set objMostRecentFile = Nothing

'browse files for ext and date-max
for each objFile in objDir.Files
'~~get extension
strExt = fs.GetExtensionName (objFile.Name)
'~~test if extensions match
if 0 = StrComp(strExt, strSearchedExt, vbTextCompare) Then
'~~test if datemodified is more recent, i.e. bigger
if objFile.DateLastModified > datMax Then
'~~keep matches
datMax = objFile.DateLastModified
Set objMostRecentFile = objFile
end if
end if
next

'~~display result
if not objMostRecentFile is nothing Then
WSH.Echo "your most recent *." & strSearchedExt & " file is:", _
vbtab, _
objMostRecentFile.Path, _
vbcr & "date of last modification was:", _
vbtab, _
datMax
else
WSH.Echo "no file ending with ""." & strSearchedExt & """ found"
end if

Mfg,
Alex

sam gonzales

unread,
Aug 27, 2007, 12:30:00 PM8/27/07
to
Tahir,
I like the thread you started for finding newest file in a folder. Would
post your code with array folders. What i need to find the newest file (4hr)
from folder to subfolders.
thanks in advance
sam

asdf

unread,
Aug 31, 2007, 12:33:36 AM8/31/07
to
Do an every 3:59 hours scan and compare dates and time
of prior selection to present one.

If it is over or under a theshold date, that be your condition for action.


"sam gonzales" <sam7...@NOSPAM.com> wrote in message
news:707f85d0496945b0...@ureader.com...

krishna kumar

unread,
Jan 6, 2009, 7:28:16 AM1/6/09
to
Hi,
Thanks a lot.This script was very useful for me.I appreciate ur spotaneous
reponse.

Regards
Krishna

url:http://www.ureader.com/msg/1677440.aspx

Neil

unread,
Sep 17, 2009, 2:22:57 AM9/17/09
to
Hi i have a vbscript already which will pick up the files are older than 1
or 2 days days only. How do i run the continues scan on the folder if it
exist and also i need to notify the user with email if that file exist or
not.
Also i forgot to mention this script creates a folder according to the
current date format.

I am intermediate to this vb scripting.

any help would be appreciated.

Set fso = CreateObject("Scripting.FileSystemObject")
StrMonth = Month(Date)
If Len(strMonth) = 1 Then
strMonth = "0" & strMonth
End If
StrDay = Day(Date)
If Len(strDay) = 1 Then
strDay = "0" & strDay
End If
StrYear = Year(Date)
strFolderName = "Path of the file where it dumps the files to" &
"Nameofthefolder-" & strDay & "-" & strMonth & "-" & StrYear & "\"
Set objFolder = FSO.CreateFolder(strFolderName)

strDir = "Path of the folder where it picks up the files from"
Set objDir = FSO.GetFolder(strDir)
getInfo(objDir)

Sub getInfo(pCurrentDir)

For Each aItem In pCurrentDir.Files
'wscript.Echo aItem.Name
If DateDiff("d", aitem.DateLastModified, Now) < 2 Then
FSO.CopyFile aitem, strfoldername
End If
Next

For Each aItem In pCurrentDir.SubFolders
'wscript.Echo aItem.Name & " passing recursively"
getInfo(aItem)
Next

End Sub

url:http://www.ureader.com/msg/1677440.aspx

Pegasus [MVP]

unread,
Sep 17, 2009, 2:35:50 AM9/17/09
to

"Neil" <nilesh_...@yahoo.com> wrote in message news:...

> Hi i have a vbscript already which will pick up the files are older than 1
> or 2 days days only. How do i run the continues scan on the folder if it
> exist and also i need to notify the user with email if that file exist or
> not.

I cannot understand your statement "How do i run the continues scan on the
folder if it exist". If what exists? Some file? Some folder? Please rephrase
and expand. And how does your question relate to your Subject line ("Find
the latest [most recent?] file in a folder")?


Neil

unread,
Sep 17, 2009, 8:17:24 PM9/17/09
to
I have a script which will scan the data for only days which are greater
than 1 or 2 days, what if the file are bit older and not get picked up if
they are older than 1 to 2 days the scripts will look at the files for only
< 2 days.

1) How do i check for LastDateCreated for file so they get picked up by this
script.
2) If the file doesnt exist for that day how do i notify the users that file
doesnt exist may be in a HTML format with the date name & file name may be
3) When the file exist i still want to trigger the email with the
notification that this file exist in the HTML format with the names of the
file & last date created.
4) Subject --> Find the latest file in a folder, which i meant if the file
is created recently wiht the new date stamp in a folder should gets copied
across to the destination folder.

Please let me know if you need some more clarification.

I would really appreciate your help.

Thanks

Set fso = CreateObject("Scripting.FileSystemObject")
StrMonth = Month(Date)
If Len(strMonth) = 1 Then
strMonth = "0" & strMonth
End If
StrDay = Day(Date)
If Len(strDay) = 1 Then
strDay = "0" & strDay
End If
StrYear = Year(Date)

strFolderName = "folders gets created with the specific format to this
location with --> destination path" & "JDEDone-" & strDay & "-" & strMonth &

"-" & StrYear & "\"
Set objFolder = FSO.CreateFolder(strFolderName)

strDir = "files gets picked up from this location --> source path"


Set objDir = FSO.GetFolder(strDir)
getInfo(objDir)

Sub getInfo(pCurrentDir)

For Each aItem In pCurrentDir.Files
'wscript.Echo aItem.Name
If DateDiff("d", aitem.DateLastModified, Now) < 2 Then
FSO.CopyFile aitem, strfoldername
End If
Next

For Each aItem In pCurrentDir.SubFolders
'wscript.Echo aItem.Name & " passing recursively"
getInfo(aItem)
Next

End Sub

url:http://www.ureader.com/msg/16771777.aspx

Pegasus [MVP]

unread,
Sep 18, 2009, 5:53:47 AM9/18/09
to
Here are some pointers:

* To create a folder whose name is today's date:


Set oFSO = CreateObject("Scripting.FileSystemObject")

oFSO.CreateFolder("C:\" & pad(Day(Now)) & pad(Month(Now)) & Year(Now))
Function pad (n)
pad = Left(0 & n, 2) & "-"
End Function

* To determine the most recent file in the specified folder:
dim sMostRecent, dMostRecent
MostRecent("D:\Temp")
WScript.Echo sMostRecent, dMostRecent
Sub MostRecent (sFolder)


Set oFSO = CreateObject("Scripting.FileSystemObject")

dMostRecent = 0
sMostRecent = ""
For Each oFile In oFSO.GetFolder(sFolder).Files
dFileDate = oFile.DateLastModified
If dFileDate > dMostRecent Then
dMostRecent = dFileDate
sMostRecent = oFile.Path
End If
Next
End Sub

* To send a message to a user:
const cdoBasic=1
schema = "http://schemas.microsoft.com/cdo/configuration/"
Set objEmail = CreateObject("CDO.Message")
With objEmail
.From = "Ja...@company.com"
.To = "J...@company.com"
.Subject = "Test Mail"
.Textbody = "The quick brown fox " & Chr(10) & "jumps over the lazy dog"
.AddAttachment "d:\Testfile.txt"
With .Configuration.Fields
.Item (schema & "sendusing") = 2
.Item (schema & "smtpserver") = "mail.company.com"
.Item (schema & "smtpserverport") = 25
.Item (schema & "smtpauthenticate") = cdoBasic
.Item (schema & "sendusername") = "Ja...@company.com"
.Item (schema & "smtpaccountname") = "Ja...@company.com"
.Item (schema & "sendpassword") = "SomePassword"
End With
.Configuration.Fields.Update
.Send
End With

"Neil" <nilesh_...@yahoo.com> wrote in message

news:4edb2e76e7694c1b...@newspe.com...

John

unread,
Sep 20, 2010, 10:06:56 PM9/20/10
to
Hi i need help!

I need a script that goes to pre defined list of folders and prints the date
and file name (so i can copy and paste) of latest file in each folder. i
have about 100 folders to go through.

please this will be a huge help!

Regards,

url:http://www.ureader.com/msg/1677440.aspx

ekkehard.horner

unread,
Sep 21, 2010, 2:21:33 AM9/21/10
to
John schrieb:

> Hi i need help!
>
> I need a script that goes to pre defined list of folders and prints the date
> and file name (so i can copy and paste) of latest file in each folder. i
> have about 100 folders to go through.
[...]

(1) How will the script get the list of predefined folders? Hardcoded
array? From a text file? From a spreadsheet? From a database table?
(2) What date? DateCreated? DateLastAccessed? DateLastModified?
(3) What about files from different folders with the same *name*?
(4) How to deal with more than one file having the same latest date?

Assuming 'easy' answers:

Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
Dim aDirs : aDirs = Array( _
".\" _
, "c:\temp" _
)
Dim sDir
For Each sDir In aDirs
Dim oLatest : Set oLatest = Nothing
Dim oFile
For Each oFile In goFS.GetFolder( sDir ).Files
Select Case True
Case oLatest Is Nothing
Set oLatest = oFile
Case oFile.DateLastModified > oLatest.DateLastModified
Set oLatest = oFile
End Select
Next
If oLatest Is Nothing Then
WScript.Echo "no files in", sDir
Else
WScript.Echo oLatest.Path, oLatest.DateLastModified
End If
Next

0 new messages