Created
June 20, 2018 07:56
-
-
Save Graham-Beer/6dc47580cd27cf87170a5372ca4d9575 to your computer and use it in GitHub Desktop.
Creation of File System Watcher class and subscribed events.
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
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