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
> 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
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
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
> 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) wrote:
' Oops, one line was missing
dPrevDate = oFile.DateLastModified
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
------------------------------------------------------------------------
Posted via http://www.codecomments.com
------------------------------------------------------------------------
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
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...
Regards
Krishna
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
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")?
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
* 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...
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,
(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