Saturday, July 17, 2010

PowerShell, events and file watcher

A simple script that create a file watcher on a specific folder and collect the events in a global variable.

 

function watch-folder {
    param([string]$path)
    $fileSystemWatcher = new-object System.IO.FileSystemWatcher
    $fileSystemWatcher.Path = $path
    $global:events = new-object system.data.datatable
    [void] $events.Columns.Add("Time", [datetime])
    [void] $events.Columns.Add("Full path", [string])
    [void] $events.Columns.Add("Change type", [string])
    $event = {
        [void] $events.Rows.Add([datetime]::Now, $eventArgs.FullPath, $eventArgs.ChangeType)
    }
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Created -Action $event)
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Changed -Action $event)
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Deleted -Action $event)
}
cls
watch-folder "c:\Temp"
"foobar" > c:\temp\test.txt
del c:\temp\test.txt
$global:events
get-eventsubscriber -force | unregister-event -force

3 comments:

  1. I get this when I run this script:

    Unexpected token 'Register-ObjectEvent' in expression or statement.
    At C:\users\administrator\Documents\scripts\Watchfolder.ps1:17 char:32
    + [void] Register-ObjectEvent <<<< -InputObject $fsw -EventName Created -Action $a
    ction
    + CategoryInfo : ParserError: (Register-ObjectEvent:String) [], ParseExce
    ption
    + FullyQualifiedErrorId : UnexpectedToken

    ReplyDelete
  2. I have three different files in different subfolders & I want it to check every 5 minutes for any changes to those files.
    I have it watching the main folder but it doesn't seem to do anything after changes are made.

    ReplyDelete
  3. Well, I forgot to mention that it should start another another .ps1; when a change has been made.

    ReplyDelete