Chapter 31. Event Handling
31.0 Introduction
Much of system administration is reactionary: taking some action when a system service shuts down, when files are created or deleted, when changes are made to the Windows Registry, or even on a timed interval.
The easiest way to respond to system changes is to simply poll for them. If youâre waiting for a file to be created, just check for it every once in a while until it shows up. If youâre waiting for a process to start, just keep calling the Get-Process
cmdlet until itâs there.
This approach is passable for some events (such as waiting for a process to come or go), but it quickly falls apart when you need to monitor huge portions of the systemâsuch as the entire registry or filesystem.
An an alternative to polling for system changes, many technologies support automatic notificationsâknown as events. When an application registers for these automatic notifications, it can respond to them as soon as they happen, rather than having to poll for them.
Unfortunately, each technology offers its own method of event notification: .NET defines one approach and WMI defines another. When you have a script that wants to generate its own events, neither technology offers an option.
PowerShell addresses this complexity by introducing a single, consistent set of event-related cmdlets. These cmdlets let you work with all of these different event sources. When an event occurs, you can let PowerShell store the notification for you in its ...
Get PowerShell Cookbook, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.