PoshCode Archive  Artifact [dca9cce94c]

Artifact dca9cce94c292c262f8610bf0b71905f756249f598656ffbbabc8a746a619dc3:

  • File CTP3-Watch-Folder.ps1 — part of check-in [b2fec69446] at 2018-06-10 14:25:23 on branch trunk — Requires PS 2.0 CTP3 (user: Oisin Grehan size: 1332)

# 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
}