views:

366

answers:

4

I am trying to write a script that will parse a local file and upload its contents to a MySQL database. Right now, I am thinking that a batch script that runs a Perl script would work, but am not sure if this is the best method of accomplishing this.

In addition, I would like this script to run immediately when the data file is added to a certain directory. Is this possible in Windows?

Thoughts? Feedback? I'm fairly new to Perl and Windows batch scripts, so any guidance would be appreciated.

+1  A: 

It wouldn't be too hard to put together a small C# application that uses the FileSystemWatcher class to detect files being added to a folder and then spawn the required script. It would certainly use less CPU / system resources / hard disk bandwidth than polling the folder at regular intervals.

Skizz

Skizz
If scripting is a requirement, PowerShell can use the .NET classes like FileSystemWatcher as well. There's a blog entry here: http://mow001.blogspot.com/2005/10/msh-directory-watcher-with-popup.html that shows how.
Harper Shelby
A: 

Checking a folder for newly created files can be implemented using the WMI functionality. Namely, you can create a Perl script that subscribes to the __InstanceCreationEvent WMI event that traces the creation of the CIM_DirectoryContainsFile class instances. Once that kind of event is fired, you know a new file has been added to the folder and can process it as you need.

These articles provide more information on the subject and contain VBScript code samples (hope it won't be hard for you to convert them to Perl):

Helen
A: 

The function you want is ReadDirectoryChangesW. A quick search for a perl wrapper yields this Win32::ReadDirectoryChanges module.

Your script would look something like this:

use Win32::ReadDirectoryChanges;

$rdc = new Win32::ReadDirectoryChanges(path    => $path,
                                       subtree => 1,
                                       filter  => $filter);

while(1) {
    @results = $rdc->read_changes;

    while (scalar @results) {
      my ($action, $filename) = splice(@results, 0, 2);
      ... run script ...
    }
}
arolson101
I can't tell if the read_changes call is blocking or not... if not, wouldn't adding a short sleep be a good idea?
R. Bemrose
It should block until there is a change in the directory.
arolson101
+7  A: 

You can use Win32::ChangeNotify. Your script will be notified when a file is added to the target directory.

Sinan Ünür