<# Create delegates that will be used when a file is altered and when when it is renamed #>
$updated = { Write-Host "File: " $EventArgs.FullPath " " $EventArgs.ChangeType ;$global:UpdateEvent = $EventArgs}
$Renamed = { Write-Host "File: " $EventArgs.OldFullPath " renamed to "$EventArgs.FullPath ; $global:RenameEvent = $EventArgs}
<# Create a fileWatcher that will monitor the directory and add its attributes#>
$fileWatcher = new-object System.IO.FileSystemWatcher
$fileWatcher.Path = "C:\Junk"
$fileWatcher.Filter = "*.txt";
$fileWatcher.IncludeSubdirecto ries = $true
$fileWatcher.NotifyFilter = [System.IO.NotifyFilters]::Las tAccess , `
[System.IO.NotifyFilters]::Las tWrite, `
[System.IO.NotifyFilters]::Fil eName , `
[System.IO.NotifyFilters]::Dir ectoryName
<# If a delegate has already been added to the FileWatchers for that event remove it and add the new one. #>
if($ChangedEvent) {$ChangedEvent.Dispose()}
$ChangedEvent = Register-ObjectEvent $fileWatcher "Changed" -Action $updated
if($CreatedEvent) {$CreatedEvent.Dispose()}
$CreatedEvent = Register-ObjectEvent $fileWatcher "Created" -Action $updated
if($DeletedEvent) {$DeletedEvent.Dispose()}
$DeletedEvent = Register-ObjectEvent $fileWatcher "Deleted" -Action $updated
if($RenamedEvent) {$RenamedEvent.Dispose()}
$RenamedEvent = Register-ObjectEvent $fileWatcher "Renamed" -Action $Renamed
$fileWatcher.EnableRaisingEven ts = $true
<#
#To stop monitoring the text files in your specified directory run the script bellow.
if($RenamedEvent) {$RenamedEvent.Dispose()}
if($DeletedEvent) {$DeletedEvent.Dispose()}
if($CreatedEvent) {$CreatedEvent.Dispose()}
if($ChangedEvent) {$ChangedEvent.Dispose()}
#>
<#
c# style go add delegates to your filewatcher
fileWatcher.Changed += new FileSystemEventHandler( Wathcer_Changed);
fileWatcher.Created += new FileSystemEventHandler( Wathcer_Changed);
fileWatcher.Deleted += new FileSystemEventHandler( Wathcer_Changed);
static void Wathcer_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Change Type = {0}, Path = {1}", e.ChangeType, e.FullPath);
}
#>