# encoding: ascii
# api: powershell
# title: CTP3: Watch Folder
# description: Requires PS 2.0 CTP3
# version: 0.1
# type: function
# author: Oisin Grehan
# license: CC0
# function: watch-folder
# x-poshcode-id: 859
# x-archived: 2016-03-02T15:53:46
# x-published: 2009-02-10T14:26:00
#
# Example code for watching a folder for changes and automatically storing in a global variable of type DataTable.
#
#requires -version 2.0
# Example
#
# ps> . .\watch-folder.ps1
# ps> watch-folder c:\temp
# ps> "foo" > c:\temp\test.txt
# ps> $table
# ps> (shows changes)
function watch-folder {
param([string]$folder)
$fsw = new-object System.IO.FileSystemWatcher
$fsw.Path = $folder
# stores changes to $folder
$global:table = new-object system.data.datatable
[void] $table.Columns.Add("FullPath", [string])
[void] $table.Columns.Add("ChangeType", [string])
$action = {
[console]::beep(440,10)
[void] $table.Rows.Add($eventArgs.FullPath, $eventArgs.ChangeType)
}
[void] Register-ObjectEvent -InputObject $fsw -EventName Created -Action $action
[void] Register-ObjectEvent -InputObject $fsw -EventName Changed -Action $action
[void] Register-ObjectEvent -InputObject $fsw -EventName Deleted -Action $action
}