Skip to content

Instantly share code, notes, and snippets.

@Nora-Ballard
Created February 15, 2014 13:25
Show Gist options
  • Save Nora-Ballard/9019286 to your computer and use it in GitHub Desktop.
Save Nora-Ballard/9019286 to your computer and use it in GitHub Desktop.
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