Created
February 15, 2014 13:25
-
-
Save Nora-Ballard/9019286 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function New-FolderWatcher | |
{ | |
param( | |
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$True)] | |
$Path, | |
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$True)] | |
[hashtable] $Events , | |
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$True)] | |
$MessageData = "", | |
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$True)] | |
[switch] $IncludeSubdirectories | |
) | |
PROCESS | |
{ | |
if (test-path $Path) | |
{ | |
$watcher = New-Object System.IO.FileSystemWatcher | |
$watcher.Path = $Path | |
$watcher.IncludeSubdirectories = $IncludeSubdirectories | |
$watcher.EnableRaisingEvents = $true | |
$SupportedEvents = $watcher | Get-Member | where {$_.membertype -eq 'Event' } | |
$DefaultAction = { write-host "$($event.SourceIdentifier) '$($eventArgs.FullPath)'" } | |
if (!$Events) | |
{ | |
$Events = @{} | |
$SupportedEvents | ForEach-Object { | |
$Events.Add($_.Name, $DefaultAction) | |
} | |
} | |
$Events.Keys | ForEach-Object { | |
$EventName = $_ | |
$Action = $Events[$_] | |
$SourceIdentifier = "FileSystemWatcher.$EventName" | |
if ($action -is [scriptblock]) | |
{ | |
Remove-Event -SourceIdentifier $SourceIdentifier -ErrorAction SilentlyContinue | |
Unregister-Event -SourceIdentifier $SourceIdentifier -ErrorAction SilentlyContinue | |
Register-ObjectEvent -InputObject $watcher -EventName $EventName -SourceIdentifier $SourceIdentifier -Action $Action -MessageData $MessageData | |
} | |
} | |
} | |
} #end Process | |
} #end Function | |
#New-FolderWatcher -Path "C:\temp\watch" | |
<# | |
New-FolderWatcher -Path "C:\temp\watch" -Events @{ | |
'Created' = { write-host "$($event.SourceIdentifier) file $($eventArgs.FullPath)" } | |
'Deleted' = { write-host "$($event.SourceIdentifier) file $($eventArgs.FullPath)" } | |
'Disposed' = { write-host "$($event.SourceIdentifier) file $($eventArgs.FullPath)" } | |
'Error' = { write-host "$($event.SourceIdentifier) file $($eventArgs.FullPath)" } | |
'Renamed' = { write-host "$($event.SourceIdentifier) file $($eventArgs.FullPath)" } | |
} | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment