Skip to content

Publishes changes in file system as powershell engine event

License

Notifications You must be signed in to change notification settings

fcbry/fswatcher-engine-event

 
 

Repository files navigation

FSWatcherEngineEvent

is a Powershell module which notifies of filesystem changes using a Powershell engine events.

For a quick walkthru: https://devblogs.microsoft.com/powershell-community/a-reusable-file-system-event-watcher-for-powershell/

A new event handler can be created with the cmdlet New-FileSystemWatcher:

CodeFactor

How to Install

FSWatcherEngineEvent is published to the Powershell Gallery. To Install it locally use PowerShellGets Install-Module command:

PS> Install-Module -Name FSWatcherEngineEvent

Watch for Changes and Receive Events

To start watching for changes in a directory a file system watcher has to be created and an event handler to process the events. Event source and event receiver are associated by the user defined source identifier.

PS> New-FileSystemWatcher -SourceIdentifier "myevent" -Path c:\temp\files

The parameter 'SourceIdentifier' is the unique name of the powershell engine event generated by the file system watcher. The other parameters of the cmdlet correspond to the properties of the .Net FileSystemWatcher class.

If you wish to watch subdirectories, you can add -IncludeSubdirectories as a switch.

PS> New-FileSystemWatcher -SourceIdentifier "myevent" -Path c:\temp\files -IncludeSubdirectories

Since Version 1.4 the option -EditOptions presents a small text UI in the terminal where the notification parameters (Filter, notification flags, include/exclude sub dirs) can be set interactively.

To receive the event an event handler must be registered for the source identifier. Powershell will write the subscription to the pipe.

PS> Register-EngineEvent -SourceIdentifier "myevent" -Action { $event | ConvertTo-Json | Write-Host }

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      myevent                         NotStarted    False                                $event|ConvertTo-Json|Wr…

The above action will dump the whole event to the console. You will receive something like this:

# change a file in the watched directory
PS> "XYZ" >> C:\temp\files\xyz

{
  "ComputerName": null,
  "RunspaceId": "b92c271b-c147-4bd6-97e4-ffc2308a1fcc",
  "EventIdentifier": 4,
  "Sender": {
    "NotifyFilter": 19,
    "Filters": [],
    "EnableRaisingEvents": true,
    "Filter": "*",
    "IncludeSubdirectories": false,
    "InternalBufferSize": 8192,
    "Path": "D:\\tmp\\files\\",
    "Site": null,
    "SynchronizingObject": null,
    "Container": null
  },
  "SourceEventArgs": null,
  "SourceArgs": null,
  "SourceIdentifier": "myevent",
  "TimeGenerated": "2021-03-13T21:39:50.4483088+01:00",
  "MessageData": {
    "ChangeType": 4,
    "FullPath": "C:\\temp\\files\\xyz",
    "Name": "xyz"
  }
}

Since version 1.2 of the module an event handler can be specified at New-FileSystemWatcher instead of registering it after creation of the watcher as a separate command:

PS> New-FileSystemWatcher -SourceIdentifier "myevent" -Path c:\temp\files -Action { $event | ConvertTo-Json | Write-Host }

While there can be only one file system watcher for a source identifier it is possible to register multiple event handlers for the same source identifier. To inspect the current registrations you may use PowerShells Get-EventSubscriber command:

PS> Get-EventSubscriber

SubscriptionId   : 1
SourceObject     : 
EventName        : 
SourceIdentifier : myevent
Action           : System.Management.Automation.PSEventJob
HandlerDelegate  : 
SupportEvent     : False
ForwardEvent     : False

You may also inspect the state of the file system watchers. It will write the current state of the watcher and its configuration to the pipe:

PS>  Get-FileSystemWatcher

SourceIdentifier      : myevent
Path                  : C:\temp\files\
NotifyFilter          : FileName, DirectoryName, LastWrite
EnableRaisingEvents   : True
IncludeSubdirectories : False
Filter                : *

Debounce or Throttle Notifications

With version 1.5 notifications from teh file system watcher can be throttled or debounced. Throttling aggregates all notifications within a given time interval and send a single notification contains a list of the collected notifications after the time interval has elapsed. Debouncing means that change notifications are held back until no further event occurs for a given time span. The now sent event contains also a list of changes that were held back. It isn't possible to combine these two options. The structure of the event is different from the notifications without debouncing or throttling:

{
  // the upper part is unchanged
  ..

  "MessageData": [{ // <- message data is an array of events instead of a single one
    "ChangeType": 4,
    "FullPath": "C:\\temp\\files\\xyz",
    "Name": "xyz"
  },
  .. // more events
  ]
}

To enable debouncing or throttling specify the method and the time interval as a parameter:

PS> Register-EngineEvent -SourceIdentifier "myevent" -Action { $event | ConvertTo-Json | Write-Host } -DebounceMs 100

PS> Register-EngineEvent -SourceIdentifier "myevent" -Action { $event | ConvertTo-Json | Write-Host } -ThrottleMs 100

Suspend and Resume Watching

The notifications can be suspended and resumed without disabling the file system watcher or removing the event handlers:

PS> Suspend-FileSystemWatcher -SourceIdentifier "myevent"

PS> Resume-FileSystemWatcher -SourceIdentifier "myevent"

Stop Watching and Clean up

If no longer needed the file system watcher can be disposed:

PS> Remove-FileSystemWatcher -SourceIdentifier "myevent"

Now you may create a new file system watcher to replaced the removed one or you may also unregister the event handlers:

PS> Get-EventSubscriber -SourceIdentifier "myevent" | Unregister-Event

Since version 1.2 all subscribers can be removed together with the file system watcher:$$

PS> Remove-FileSystemWatcher -SourceIdentifier "myevent" -UnregisterAll

Since version 1.3 a call to New-FileSystemWatcher registers a script block at PowerShells Exiting event to clean up all file system watchers automatically.

About

Publishes changes in file system as powershell engine event

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 97.1%
  • PowerShell 2.9%