Skip to content

Instantly share code, notes, and snippets.

@Graham-Beer
Created June 20, 2018 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Graham-Beer/6dc47580cd27cf87170a5372ca4d9575 to your computer and use it in GitHub Desktop.
Save Graham-Beer/6dc47580cd27cf87170a5372ca4d9575 to your computer and use it in GitHub Desktop.
Creation of File System Watcher class and subscribed events.
enum EventName {
Created
Changed
Deleted
Renamed
}
function Invoke-FileSystemWatcher {
[CmdletBinding()]
param (
[Parameter()]
[System.IO.FileInfo] $Path,
[Parameter()]
[String] $filter = '*.*',
[Parameter()]
[System.IO.NotifyFilters] $NotifyFilters,
[parameter()]
[Switch] $Recurse,
[parameter()]
[Switch] $EnableRaisingEvents,
[Parameter()]
[EventName] $EventName,
[Parameter()]
[psobject] $MessageData,
[Parameter()]
[scriptblock] $Action
)
$watcher = [System.IO.FileSystemWatcher]::new()
Write-Verbose -Message "[PROCESS] Building FileSystemWatcher with parameters"
# Build the FileSystemWatcher class
Switch ($PSBoundParameters) {
{ $_.ContainsKey('Path') } {
$watcher.Path = $Path.FullName
}
{ $_.ContainsKey('Filter') } {
$watcher.Filter = $filter
}
{ $_.ContainsKey('NotifyFilters') } {
$watcher.NotifyFilter = $NotifyFilters
}
{ $_.ContainsKey('Recurse') } {
$watcher.IncludeSubdirectories = $Recurse.ToBool()
}
{ $_.ContainsKey('Recurse') } {
$watcher.EnableRaisingEvents = $EnableRaisingEvents.ToBool()
}
}
Write-Verbose -Message "[PROCESS] Built FileSystemWatcher, registering Event"
# Register the Event
$ObjectEvent = @{
InputObject = $watcher
EventName = $EventName
SourceIdentifier = "Watching: $($Path.FullName)"
Action = $Action
MessageData = $MessageData
}
$null = Register-ObjectEvent @ObjectEvent
Write-Verbose -Message "[PROCESS] Event now registered"
}
# Example | monitor directory size and alert to host
$watcherEvent = @{
Path = 'C:\temp'
filter = "*.*"
NotifyFilters = 'LastWrite', 'DirectoryName'
Recurse = $true
MessageData = "8mb"
EnableRaisingEvents = $true
EventName = 'Changed'
Action = {
$Folder = (Get-ChildItem $Sender.Path -Recurse |
Measure-Object -Property Length -Sum -ErrorAction Stop).Sum
if ($Folder -ge $Event.MessageData) {
$limitOver = '{0:N2}MB' -f (($Folder - $Event.MessageData) / 1mb)
$message = "[WARNING] [{0}] {1} has exceeded the limit of {2} by {3}" -f
$Event.TimeGenerated,
$Sender.Path,
$Event.MessageData,
$limitOver
$message | Out-Host
}
}
}
Invoke-FileSystemWatcher @watcherEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment