Windows Command Line Script - File exists for > 5 mins

cjb123
cjb123 used Ask the Experts™
on
Hello,

I'm looking to build a script that would send an alert email if there are files within a given directory for > 5 mins.  I'm a bit of a noob when it comes to scripting in Windows either through batch scripts or cscripts, any help would be appreciated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Bill PrewTest your restores, not your backups...
Top Expert 2016

Commented:
Unless you wanted to have a script running all the time and "sleeping" in between checks, you'd probably want to drive this from windows task scheduler to run the script every so often.  How often do you want to check, every 5 minutes, every 1 minute, etc?

It could be done in BAT, but VBS would be a lot easier since it can handle date math quite a bit easier than a BAT script.  Would that work?

While I'm at it, if it were me, I'd probably use a directory monitoring tool for this rather than a script, likely be faster and easier to get working properly and dependably.

Here are some free ones you could look at:

http://www.brutaldev.com/page/Directory-Monitor.aspx
http://download.cnet.com/Directory-Monitor/3000-2248_4-10849871.html
http://www.contactplus.com/products/freestuff/monidir.htm
http://www.nodesoft.com/foldermonitor
http://www.gibinsoft.net/
http://leelusoft.blogspot.com/2010/07/watch-4-folder-22.html

And here are some paid ones:

http://www.watchdirectory.net/
http://www.coolutils.com/TotalFolderMonitor
http://www.networkautomation.com/
http://www.liquidmirror.com/alwayswatching.asp

~bp
Commented:
Here is a quick vbscript that will check each file in a folder you specify and throw an alert if any were created more than 5 minutes ago.  You'll want to set the variables for the server path (you can use UNC paths), an [open] SMTP relay server, email address, etc.
strRoot = "your_path"
strSMTP = "your.mail.server"
strMailTo = "you@domain.com"
strSender = "script@domain.com"
strSubject = "File Alert"
blnAlert = False

Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objfso.GetFolder(strRoot)
For Each sFile In objFolder.Files
  Set oFile = objfso.GetFile(sFile)
   If DateDiff("n",oFile.DateCreated,Now)>5 Then
   	strBody = strBody & oFile.Name & " created " & oFile.DateCreated & vbCrLf
   	blnAlert = True
   End If
Next

If blnAlert Then
 Set iMsg = CreateObject("CDO.Message")
 Set iConfig = CreateObject("CDO.Configuration")
 Set Flds = iConfig.Fields
 With Flds
  .Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
  .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")=strSMTP
  .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout")=10
  .Update
 End With
 With iMsg
  Set .Configuration = iConfig
  .To = strMailTo
  .From = strSender
  .Subject = strSubject
  .TextBody = strBody
  .Send
 End With
End If

Set objfso = Nothing

Open in new window


Are you set on using vbs?  Powershell is cleaner and simpler:
$blnAert = $false
gci e:\software | where { ! $_.PSIsContainer} | ForEach-Object {
  $datediff = New-TimeSpan $($_.CreationTime) $(Get-Date)
  if ($datediff.days -gt 5) {
  	$strBody += "$_.name created $_.CreationTime `n"
  	$blnAlert = $true
  }
}

if ($blnAert) {
  Send-MailMessage -To "you@domain.com" -From "script@domain.com" -Subject "File Alert" -Body $strBody -SmtpServer "server.domain.com"
}

Open in new window

Author

Commented:
I could see the powershell solution kollenh proposed working.  I changed one line of code though from $datediff.days to $datediff.totalminutes since I'm looking to see if there's a file in there that has existed for an unusual amount of time.  I would have accepted this, but the server I'm going to run this on doesn't have PS installed -__- hopefully I will give you your points tomorrow AM, I know you can't wait!
11/26 Forrester Webinar: Savings for Enterprise

How can your organization benefit from savings just by replacing your legacy backup solutions with Acronis' #CyberProtection? Join Forrester's Joe Branca and Ryan Davis from Acronis live as they explain how you can too.

Commented:
Oh yeah, sorry - I changed it to days to test on my system and forgot to change it back.  As billprew mentioned, you'll probably want to schedule it to run.  Also the directory monitoring tool is a good solution but with a script you have more control - you can monitor for additional parameters as the scope changes.  Which it usually does.

HTH
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
This example VBS will log all files older than 5 minutes. It will not log "old" files existing already when the script runs, only newly created ones. And you have to integrate the email stuff as shown above instead of logging. Using WMI Events, this solution has almost no overhead.
strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\cimv2")

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceCreationEvent Within 300 Where " _
    & "Targetinstance Isa 'CIM_DirectoryContainsFile' and " _
    & "TargetInstance.GroupComponent= " _
    & "'Win32_Directory.Name=""c:\\\\YourFolder\\\\ToMonitor""'")

Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop

Open in new window

Author

Commented:
I went with the PowerShell route, which worked well - small tweaks the script and I was up and running quickly.  Now I need to learn PowerShell since it looks like a great scripting language.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial