Sunday 15 October 2017

windows - How to monitor a folder and trigger a command-line action when a file is created or edited?


I need to set up some sort of a script on my Vista machine, so that whenever a file is added to a particular folder, it automatically triggers a background process that operates on the file. (The background process is just a command-line utility that takes the file name as an argument, along with some other predefined options.)


I'd like to do this using native Windows features, if possible, for performance and maintenance reasons. I've looked into using Task Scheduler, but after perusing the trigger system for a while, I haven't been able to make much sense of it, and I'm not even sure if it's capable of doing what I need.


I'd appreciate any suggestions. Thanks!



Answer



At work we use Powershell to monitor folders.
It can be used since Windows Vista (.NET and PowerShell is preinstalled) without any additional tools.


This script monitors a certain folder and writes a logfile. You can replace the action and do whatever you want e.g call an external tool


Example log file



11/23/2014 19:22:04, Created, D:\source\New Text Document.txt
11/23/2014 19:22:09, Changed, D:\source\New Text Document.txt
11/23/2014 19:22:09, Changed, D:\source\New Text Document.txt
11/23/2014 19:22:14, Deleted, D:\source\New Text Document.txt


### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "D:\source"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "D:\log.txt" -value $logline
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {sleep 5}



  1. Create a new text file

  2. Copy & paste the above code

  3. Change the following settings to your own needs:

    • folder to monitor: $watcher.Path = "D:\source"

    • file filter to include only certain file types: $watcher.Filter = "*.*"

    • include subdirectories yes/no: $watcher.IncludeSubdirectories = $true



  4. Save and rename it to StartMonitoring.ps1

  5. Start monitoring by Right click » Execute with PowerShell


To stop monitoring, it's enough to close your PowerShell window


Further reading



No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...