Monday, November 7, 2011

VBScript to find Fileage and send an e-mail

'On Error Resume Next

Const ForReading = 1
today = now()

Set objMessage = CreateObject("CDO.Message")
objMessage.From = "babu.dhinakaran@jda.com"
objMessage.To = "babu.dhinakaran@jda.com"



Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile("c:\filelist.txt", ForReading)

Do Until objTextFile.AtEndOfStream

folderspec = objTextFile.Readline
'Wscript.Echo "File in the Folder:" & folderspec
objMessage.Subject = folderspec
Agecount = 0


Set folder = objFSO.GetFolder(folderspec)
Set fc = folder.Files

For Each f1 in fc
file = f1.name
filespec = folderspec & file

Set file = objFSO.GetFile(filespec)

ShowDateCreated = file.DateCreated
'Wscript.Echo "FileName: " & filespec
'Wscript.Echo "ShowDateCreated:" & ShowDateCreated
difference = DateDiff("n",ShowDateCreated,today)

If difference > 30 Then
Agecount = Agecount + 1
End If
'Wscript.Echo "File Age in minutes is:" & difference
Next

'Wscript.Echo "Total file older than 30 minutes at: " & folderspec & " are:" & Agecount

'mailbody = "Total file older than 30 minutes at: " & folderspec & " are:" & Agecount
'objMessage.TextBody = mailbody

'Wscript.Echo "-----------------------------------------------"

objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "indiamailrelay.jda.corp.local"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update

If Agecount > 0 Then

mailbody = "Total file older than 30 minutes at: " & folderspec & " are:" & Agecount
objMessage.TextBody = mailbody
objMessage.Send
'Wscript.Echo "Total file older than 30 minutes at: " & folderspec & " are:" & Agecount

End If


Loop

------------------------------------------------------------------------------------

The above code basically, check for a fileage > 30 minutes and send an email if it is true.

It uses a text file as a input to read folder path where files exists
eg:- c:\temp\
Note: Make sure to provide full path as said above, if provided c:\temp this will generate an error.